如何在Django中动态组合OR查询过滤器?

134 投票
14 回答
57021 浏览
提问于 2025-04-15 11:32

从一个例子中,你可以看到一个包含多个“或”条件的查询过滤器:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

比如,这样的查询结果是:

[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]

但是,我想从一个列表中创建这个查询过滤器。该怎么做呢?

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

14 个回答

48

用一种更简洁的方式来写Dave Webb的回答,使用了Python的reduce函数

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

如果你想构建更复杂的查询,可以使用内置的 Q() 对象里的常量 Q.OR 和 Q.AND,配合 add() 方法来实现,像这样:

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
200

你可以像下面这样把你的查询连接起来:

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)

撰写回答