django conditionally filtering objects

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

    You can chain queries:

    user = User.objects.get(pk=1)
    category = Category.objects.get(pk=1)
    qs = Item.objects.filter(user=user, date=now())
    if category:
        qs = qs.filter(category=category)
    

    As queryset are executed lazily, DB hit will occur only when you display items.

提交回复
热议问题