首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Django中动态编写OR查询过滤器?

如何在Django中动态编写OR查询过滤器?
EN

Stack Overflow用户
提问于 2009-05-12 12:08:51
回答 12查看 50.6K关注 0票数 120

从一个示例中,您可以看到一个多OR查询过滤器:

代码语言:javascript
运行
复制
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

例如,这将导致:

代码语言:javascript
运行
复制
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]

但是,我希望从列表创建此查询筛选器。如何做到这一点?

例如[1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2009-05-12 12:21:28

您可以按如下方式链接您的查询:

代码语言:javascript
运行
复制
values = [1,2,3]

# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]

# Take one Q object from the list
query = queries.pop()

# Or the Q object with the ones remaining in the list
for item in queries:
    query |= item

# Query the model
Article.objects.filter(query)
票数 184
EN

Stack Overflow用户

发布于 2015-03-20 00:26:08

要构建更复杂的查询,还可以选择使用内置Q()对象的常量Q.OR和Q.AND以及add()方法,如下所示:

代码语言:javascript
运行
复制
list = [1, 2, 3]
# it gets a bit more complicated if we want to dynamically build
# OR queries with dynamic/unknown db field keys, let's say with a list
# of db fields that can change like the following
# list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3']

# init our q objects variable to use .add() on it
q_objects = Q(id__in=[])

# loop trough the list and create an OR condition for each item
for item in list:
    q_objects.add(Q(pk=item), Q.OR)
    # for our list_with_strings we can do the following
    # q_objects.add(Q(**{item: 1}), Q.OR)

queryset = Article.objects.filter(q_objects)

# sometimes the following is helpful for debugging (returns the SQL statement)
# print queryset.query
票数 89
EN

Stack Overflow用户

发布于 2009-05-22 13:36:13

使用python's reduce function编写Dave Webb答案的一种更简单的方法

代码语言:javascript
运行
复制
# For Python 3 only
from functools import reduce

values = [1,2,3]

# Turn list of values into one big Q objects  
query = reduce(lambda q,value: q|Q(pk=value), values, Q())  

# Query the model  
Article.objects.filter(query)  
票数 47
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/852414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档