Jac*_* Ha 92 python django django-q
从示例中,您可以看到多个OR查询过滤器:
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
Run Code Online (Sandbox Code Playgroud)
例如,这会导致:
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
Run Code Online (Sandbox Code Playgroud)
但是,我想从列表中创建此查询过滤器.怎么做?
例如 [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
Dav*_*ebb 143
您可以按如下方式链接查询:
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)
Run Code Online (Sandbox Code Playgroud)
exs*_*ide 79
要构建更复杂的查询,还可以选择使用内置的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
Run Code Online (Sandbox Code Playgroud)
Tom*_*ner 44
使用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)
Run Code Online (Sandbox Code Playgroud)
Ign*_*ams 35
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))
Run Code Online (Sandbox Code Playgroud)
ale*_*asi 19
也许最好使用sql IN语句.
Article.objects.filter(id__in=[1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
请参阅queryset api参考.
如果你真的需要用动态逻辑进行查询,你可以做这样的事情(丑陋+未经测试):
query = Q(field=1)
for cond in (2, 3):
query = query | Q(field=cond)
Article.objects.filter(query)
Run Code Online (Sandbox Code Playgroud)
查看文档:
>>> 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([])
{}
Run Code Online (Sandbox Code Playgroud)
请注意,此方法仅适用于主键查找,但这似乎是您尝试执行的操作.
所以你想要的是:
Article.objects.in_bulk([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
如果我们想以编程方式设置我们想要查询的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))
Run Code Online (Sandbox Code Playgroud)
values = [1, 2, 3]
q = Q(pk__in=[]) # generic "always false" value
for val in values:
q |= Q(pk=val)
Article.objects.filter(q)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
这两者都相当于Article.objects.filter(pk__in=values)
Q()
危险重要的是要考虑当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
Run Code Online (Sandbox Code Playgroud)
如果您想在为空时返回所有内容values
,您应该与~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
Run Code Online (Sandbox Code Playgroud)
Q()
是什么也不是,不是一个永远成功的 Q 对象。任何涉及它的操作都会将其彻底删除。
在此处与reduce
and 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()))
)
Run Code Online (Sandbox Code Playgroud)
ps f
是在python3.6中添加的新格式字符串文字
归档时间: |
|
查看次数: |
37959 次 |
最近记录: |