django conditionally filtering objects

前端 未结 5 981
野的像风
野的像风 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:43

    They are several approach to your issue. One approach is to play with Complex lookups with Q objects

    from django.db.models import Q
    
    user = User.objects.get(pk=1)
    category = Category.objects.get(pk=1)
    
    f1 = Q( user=user, date=now() )
    f_cat_is_none = Q( category__isnull = True )
    f_cat_is_not_none = Q( category=category )
    
    todays_items = Item.objects.filter( f1 & ( f_cat_is_none | f_cat_is_not_none ) )
    

    I don't right understand in your answer if this is the query you are looking for, but, with this example you can compose easily your own query.

    Edited due OP comment

    category__isnull == True means that, in database, the item has not an associated category. Perhaps the query you are looking for is:

    from django.db.models import Q
    
    user_pk = 1
    category_pk = 1  #some times None
    
    f = Q( user__pk = user_pk, date=now() )
    if category_pk is not None:
      f &= Q( category__pk = category_pk )
    
    todays_items = Item.objects.filter( f  )
    

    This is only a code sample, fit it to your requirements. Be careful with single _ and double __.

提交回复
热议问题