有条件地过滤对象 [英] django conditionally filtering objects
问题描述
我想使用一组过滤器从数据库中检索一堆行。
I would like to retrieve a bunch of rows from my database using a set of filters.
我想知道条件过滤器是否适用于django。也就是说,如果变量不为None,否则不应用过滤。
I was wondering if conditional filter is applicable in django. That is, "filter if variable is not None, or not apply filtering otherwise".
如下所示:
user = User.objects.get(pk=1)
category = Category.objects.get(pk=1)
todays_items = Item.objects.filter(user=user, date=now()).conditional_filter(category=category))
我想做的是仅当类别不为无时才应用类别过滤器。
What I would like to do is apply category filter only if category is not None.
如果类别为None(表示没有在请求对象中给出),那么此过滤器将不会被应用。这将为我节省一大堆if-elif-else的情况。
If category is None (means it is not given in the request object) then this filter would not be applied at all. This would save me a bunch of 'if-elif-else' situations.
有没有办法?
推荐答案
您可以链接查询:
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)
由于查询执行懒惰,DB只有当您显示项目时,才会发生打击。
As queryset are executed lazily, DB hit will occur only when you display items.
这篇关于有条件地过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!