2

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

3 Answers 3

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The answer is correct. You could also build the query separetedly, using the Q from django.db.models.query_utils import Q. This way you could chain your ifs with statements like this query &= Q(foo=var1)
4

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.

1 Comment

I honestly don't know why is this answer is not tagged right. It is more elegant way to filter multiple variables. Tagged answer can work for 2 or 3 variables, but imagine you have 15, what is going to happen? You will take your code complexity over the top and it will be difficult to maintain in future. Also, this answer highlights filtering by dict feature, whis is helpful, because data comes to endpoints as JSON objects, which is equal to Python dicts.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.