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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With