Django's query set filter with icontains stops working if there isn't at least one regisrty with unempty data at target column, what's the logic?

25 views Asked by At

Okay, so I made a search form with some select fields I use to filter what plant species will appear in the search result page, like only species of a specific family.

How it works: no value selected on any of the fileds, it returns all species. If you select something, it will filter species with that property or properties.

So far it was working because I only filtered mandatory fields like family that all the species were required to have, the moment I added a query related to a field with no information on any of the species it made all searches return nothing, even without selecting any of the filters.

enter image description here

So just to see if it would change anything, I inserted the information on the new fields using Django admin, and it started working as intended (meaning the filter was working and selecting nothing was showing all species again).

Here is my query set logic that works as long as there is a single species with data in searched columns:

exemplares = Exemplar.objects.all()

q = Q(tipoDeExemplar__opção__icontains=tipoDeExemplar) & \
    Q(especie__familia__opção__icontains=familia) & \
    Q(especie__genero__opcao__icontains=genero) & \
    Q(especie__epiteto__opcao__icontains=epiteto) & \
    Q(especie__variedade__opção__icontains=variedade) & \
    Q(especie__grupoVegetal__opcao__icontains=grupoVegetal) & \
    Q(especie__familiaLegada__opção__icontains=familiaLegada) & \
    Q(especie__generoLegado__opcao__icontains=generoLegado) & \
    Q(especie__epitetoLegado__opcao__icontains=epitetoLegado)

exemplares = exemplares.filter(q)

return exemplares

When the field on the front-end is empty, it's value is an empty string:

<option value="" selected></option>

This is one of the fields' model:

familiaLegada = models.ForeignKey(Familia, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Família Legada", related_name='familiaLegada')

I don't get why it works as long as there is one species with something in the fields I used to make the query, I wonder if there is something to do with null on the database, what could be the problem?

0

There are 0 answers