'Django filtering based on optional parameters

I have a list of optional parameters that I am using to filter in Django and am trying to come up with the best solution to apply these filters. My very first thought was to do something like:

if param_1 != 'all' and param_2 != 'all': # etc.
    class_var = ClassName.objects.filter(param_1__name=param_1, param_2__name=param_2) # etc.
else:
    class_var = ClassName.objects.all()

but since the parameters are all optional I might only want to filter based on param_1 and leave the rest set to 'all'. Of course the other option is to say something like:

class_var = ClassNam.objects.all()
if param_1 != 'all':
    class_var.filter(param_1__name=param_1)

if param_2 != 'all':
    class_var.filter(param_2__name=param_2)

# etc.

but that doesn't seem really efficient in my mind. I was just hoping to get some ideas on other ways I might be able to perform these option filters.



Solution 1:[1]

You may want to look into Q objects. Briefly, the Q lets you use OR statements in your queries. From the aforelinked page:

Polls.objects.filter(
    Q(question__startswith='Who') | Q(question__startswith='What')
)

This will pull questions starting with "Who" OR "What".

Solution 2:[2]

What you actually can do

from django.db.models import Q

q = Q()
if param_1 != 'all':
    q &= Q(param_1__name=param_1)

if param_2 != 'all':
    q &= Q(param_2__name=param_2)

class_var = ClassName.objects.filter(q)

OR

q = {}
if param_1 != 'all':
    q.update({'param_1__name': param_1})

if param_2 != 'all':
    q.update({'param_2__name': param_2})

class_var = ClassName.objects.filter(**q)

Solution 3:[3]

Use Q objects an make an list of queries.

q=[]
if param_1 != 'all':
   q.append(Q(param_1__name=param_1))
if param_2 != 'all':
   q.append(Q(param_2__name=param_2))

details = ClassName.objects.filter(reduce(AND, q))

Solution 4:[4]

Querysets are lazy. There won't be a database query until the queryset is evaluated, usually by iterating. You're free to apply as many filters as you like at virtually no cost.

One note: filter() does not change the queryset, but rather returns a new queryset. The correct way to apply additional filters would be:

class_var = class_var.filter(param_1__name=param_1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Abhishek
Solution 4 knbk