JuConte
JuConte

Reputation: 542

Django filter queryset only if variable is not null

I have a queryset it filter by 2 variables

family = ModelsClass.objects.filter(foo=var1).filter(bar=var2)

If var1 and var2 are not null everything work but var1 and var2 can be Null. In this case i need to exclude the Null one.

For example, if var1 is Null it must filter only by var2 and the other way around.

Is there a way to insert an if condition inside the filter queryset or something else?

TY

Upvotes: 2

Views: 4958

Answers (3)

griffins
griffins

Reputation: 8246

A different approach using Q

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code.

filters = Q()
if my_first_param:
   filters &= Q(my_first_param=my_first_param)
if my_second_param:
   filters &= Q(my_second_param=my_second_param)

# Perform filtration
family_queryset = ModelClass.objects.filter(filters)

Upvotes: 0

arcstur
arcstur

Reputation: 81

More generally, you can create a filter dictionary and filter the dictionary keys for null values using a dict comprehension.

filters = {
  'foo': var1,
  'bar': var2,
}
filters = {k:v for k,v in filters.items() if v is not None}
family_queryset = ModelClass.objects.filter(**filters)

You can even use if v instead of if v is not None to also exclude empty strings, for example.

Upvotes: 4

Cagatay Barin
Cagatay Barin

Reputation: 3496

Why don't you check if variable is null and then filter it? You don't have to do it in one line. Django's queryset objects are lazy evaluated and you can filter or do other things in separate lines.

family_queryset = ModelClass.objects.all()

if var1:
    family_queryset = family_queryset.filter(foo=var1)

if var2:
    family_queryset = family_queryset.filter(bar=var2)

Upvotes: 6

Related Questions