120

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

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

4

14 回答 14

184

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

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)
于 2009-05-12T12:21:28.030 回答
90

要构建更复杂的查询,还可以选择使用内置 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
于 2015-03-19T16:26:07.727 回答
47

使用python 的 reduce 函数编写 Dave Webb 答案的一种更短的方法:

# 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)  
于 2009-05-22T13:36:12.713 回答
43
from functools import reduce
from operator import or_
from django.db.models import Q

values = [1, 2, 3]
query = reduce(or_, (Q(pk=x) for x in values))
于 2009-05-22T14:34:19.337 回答
23

也许最好使用 sql IN 语句。

Article.objects.filter(id__in=[1, 2, 3])

请参阅查询集 API 参考

如果你真的需要用动态逻辑进行查询,你可以做这样的事情(丑陋+未经测试):

query = Q(field=1)
for cond in (2, 3):
    query = query | Q(field=cond)
Article.objects.filter(query)
于 2009-05-12T12:12:40.350 回答
10

请参阅文档

>>> Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
>>> Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
>>> Blog.objects.in_bulk([])
{}

请注意,此方法仅适用于主键查找,但这似乎是您想要做的。

所以你想要的是:

Article.objects.in_bulk([1, 2, 3])
于 2009-05-12T12:11:18.750 回答
8

使用reduceor_运算符按乘法字段过滤的解决方案。

from functools import reduce
from operator import or_
from django.db.models import Q

filters = {'field1': [1, 2], 'field2': ['value', 'other_value']}

qs = Article.objects.filter(
   reduce(or_, (Q(**{f'{k}__in': v}) for k, v in filters.items()))
)

psf是一种新的格式字符串文字。它是在 python 3.6 中引入的

于 2017-12-04T12:20:36.520 回答
7

如果我们想以编程方式设置我们想要查询的数据库字段:

import operator
questions = [('question__contains', 'test'), ('question__gt', 23 )]
q_list = [Q(x) for x in questions]
Poll.objects.filter(reduce(operator.or_, q_list))
于 2012-09-24T16:01:10.333 回答
4

您可以使用 |= 运算符以编程方式使用 Q 对象更新查询。

于 2009-05-12T12:12:30.603 回答
2

这个是动态pk列表的:

pk_list = qs.values_list('pk', flat=True)  # i.e [] or [1, 2, 3]

if len(pk_list) == 0:
    Article.objects.none()

else:
    q = None
    for pk in pk_list:
        if q is None:
            q = Q(pk=pk)
        else:
            q = q | Q(pk=pk)

    Article.objects.filter(q)
于 2014-08-02T10:30:20.723 回答
1

直到最近我才知道的另一个选项 -QuerySet也覆盖了&, |,~等运算符。OR Q 对象的其他答案是该问题的更好解决方案,但为了感兴趣/争论,您可以这样做:

id_list = [1, 2, 3]
q = Article.objects.filter(pk=id_list[0])
for i in id_list[1:]:
    q |= Article.objects.filter(pk=i)

str(q.query)将返回一个包含WHERE子句中所有过滤器的查询。

于 2016-08-26T10:45:46.457 回答
1

对于循环:

values = [1, 2, 3]
q = Q(pk__in=[]) # generic "always false" value
for val in values:
    q |= Q(pk=val)
Article.objects.filter(q)

减少:

from functools import reduce
from operator import or_

values = [1, 2, 3]
q_objects = [Q(pk=val) for val in values]
q = reduce(or_, q_objects, Q(pk__in=[]))
Article.objects.filter(q)

这两个都等价于Article.objects.filter(pk__in=values)

values当空的时候考虑你想要什么是很重要的。Q()许多以作为起始值的答案将返回所有内容Q(pk__in=[])是一个更好的起始值。它是一个总是失败的 Q 对象,由优化器很好地处理(即使对于复杂的方程)。

Article.objects.filter(Q(pk__in=[]))  # doesn't hit DB
Article.objects.filter(Q(pk=None))    # hits DB and returns nothing
Article.objects.none()                # doesn't hit DB
Article.objects.filter(Q())           # returns everything

如果您在为空时返回所有内容values,您应该 AND with~Q(pk__in=[])以确保该行为:

values = []
q = Q()
for val in values:
    q |= Q(pk=val)
Article.objects.filter(q)                     # everything
Article.objects.filter(q | author="Tolkien")  # only Tolkien

q &= ~Q(pk__in=[])
Article.objects.filter(q)                     # everything
Article.objects.filter(q | author="Tolkien")  # everything

重要的是要记住 that Q()is nothing,不是一个总是成功的 Q 对象。任何涉及它的操作都会完全放弃它。

于 2020-01-16T04:01:50.653 回答
0

easy..
from django.db.models import Q import you model args = (Q(visibility=1)|(Q(visibility=0)&Q(user=self.user))) #Tuple parameters={} #dic order = 'create_at' 限制 = 10

Models.objects.filter(*args,**parameters).order_by(order)[:limit]
于 2015-12-18T15:50:12.393 回答
0

找到动态字段名称的解决方案

def search_by_fields(value, queryset, search_in_fields):
    if value:
        value = value.strip()

    if value:
        query = Q()
        for one_field in search_in_fields:
            query |= Q(("{}__icontains".format(one_field), value))

        queryset = queryset.filter(query)

    return queryset
于 2021-01-06T16:06:51.740 回答