从示例中,您可以看到多个OR查询过滤器:
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
例如,这导致:
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
但是,我想从列表中创建此查询过滤器。怎么做?
e.g。 [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
答案 0 :(得分:131)
您可以按如下方式链接查询:
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)
答案 1 :(得分:68)
要构建更复杂的查询,还可以选择使用内置的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()
# 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
答案 2 :(得分:42)
使用python's reduce function编写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)
答案 3 :(得分:29)
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))
答案 4 :(得分:19)
使用sql IN语句可能更好。
Article.objects.filter(id__in=[1, 2, 3])
如果你真的需要用动态逻辑进行查询,你可以做这样的事情(丑陋+未经测试):
query = Q(field=1)
for cond in (2, 3):
query = query | Q(field=cond)
Article.objects.filter(query)
答案 5 :(得分:8)
请参阅docs:
>>> 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])
答案 6 :(得分:6)
如果我们想以编程方式设置我们想要查询的db字段:
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))
答案 7 :(得分:5)
在此处使用包含reduce
和or_
运算符的解决方案,您如何通过乘法字段进行过滤。
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()))
)
P.S。 f
是python3.6中新格式的字符串文字
答案 8 :(得分:4)
您可以使用| =运算符以编程方式使用Q对象更新查询。
答案 9 :(得分:1)
这个是动态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)
答案 10 :(得分: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
子句中所有过滤器的查询。
答案 11 :(得分:1)
For循环:
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
为空时返回所有内容,则应与~Q(pk__in=[])
AND并确保该行为:
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
重要的是要记住,Q()
不是什么,也不是总是成功的Q对象。任何涉及此操作的操作都会将其完全删除。
答案 12 :(得分:0)
容易..
来自django.db.models导入Q.
导入你的模型
args =(Q(visibility = 1)|(Q(visibility = 0)&amp; Q(user = self.user)))#Tuple
parameters = {} #dic
order ='create_at'
limit = 10
if
答案 13 :(得分: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