django conditionally filtering objects

前端 未结 5 941
野的像风
野的像风 2020-12-29 20:16

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

5条回答
  •  有刺的猬
    2020-12-29 20:35

    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))
    

提交回复
热议问题