Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 315
JuConte Avatar asked Mar 24 '26 21:03

JuConte


2 Answers

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)
like image 80
Çağatay Barın Avatar answered Mar 27 '26 09:03

Çağatay Barın


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.

like image 32
arcstur Avatar answered Mar 27 '26 10:03

arcstur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!