I would like to retrieve a bunch of rows from my database using a set of filters.
I was wondering if conditional filter is applicable in django. That is, \"filter if
Well, this is rather old question but for those who would like to do the conditional filtering on one line, here is my approach (Btw, the following code can probably be written in a more generic way):
from django.db.models import Q
def conditional_category_filter(category):
if category != None:
return Q(category=category)
else:
return Q() #Dummy filter
user = User.objects.get(pk=1)
category = Category.objects.get(pk=1)
todays_items = Item.objects.filter(conditional_category_filter(category), user=user, date=now())
The only thing you need to watch is to use the conditional_category_filter(category)
call before the keyword arguments like user=user
. For example the following code would throw an error:
todays_items = Item.objects.filter(user=user, date=now(), conditional_category_filter(category))