如何在Django查询中做OR过滤器?

我希望能够列出用户已添加的项(它们被列为创建者)或已批准的项。

所以我基本上需要选择:

item.creator = owner or item.moderated = False

在Django中如何做到这一点?(最好是带有过滤器或查询集)。

252388 次浏览

Q对象允许进行复杂的查找。例子:

from django.db.models import Q


Item.objects.filter(Q(creator=owner) | Q(moderated=False))

你可以使用|操作符直接组合查询集,而不需要Q对象:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(编辑-我最初不确定这是否会导致额外的查询,但@spookylukey指出,懒惰的queryset计算会照顾到这一点)

你想让过滤器是动态的你就必须使用

from django.db.models import Q


brands = ['ABC','DEF' , 'GHI']


queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands])等价于

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

类似于以前的答案,但更简单一点,没有lambda…

使用OR过滤这两个条件:

Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))

要以编程方式得到相同的结果:

filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))

operator在标准库中:import operator
从文档字符串:< / p >

or_(a, b)——和a | b一样。

对于Python3, reduce不再是内置的,但仍然在标准库中:from functools import reduce


注:

不要忘记确保list_of_Q不是空的——reduce()在空列表时会阻塞,它至少需要一个元素。

值得注意的是,可以添加表达式。

例如:

from django.db.models import Q


query = Q(first_name='mark')
query.add(Q(email='mark@test.com'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)


queryset = User.objects.filter(query)

结果是这样的查询:

(first_name = 'mark' or email = 'mark@test.com') and last_name = 'doe'

这样就不需要处理操作符、reduce等。

Item.objects.filter(field_name__startswith='yourkeyword')

有多种方法。

1. 直接使用管道|操作符。

from django.db.models import Q


Items.objects.filter(Q(field1=value) | Q(field2=value))


2. 使用__or__方法。

Items.objects.filter(Q(field1=value).__or__(field2=value))

3.通过更改默认操作。(注意重置默认行为)

Q.default = Q.OR # Not recommended (Q.AND is default behaviour)
Items.objects.filter(Q(field1=value, field2=value))
Q.default = Q.AND # Reset after use.

4. 通过使用Q类参数_connector

logic = Q(field1=value, field2=value, field3=value, _connector=Q.OR)
Item.objects.filter(logic)

Q实现快照

class Q(tree.Node):
"""
Encapsulate filters as objects that can then be combined logically (using
`&` and `|`).
"""
# Connection types
AND = 'AND'
OR = 'OR'
default = AND
conditional = True


def __init__(self, *args, _connector=None, _negated=False, **kwargs):
super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)


def _combine(self, other, conn):
if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True):
raise TypeError(other)


if not self:
return other.copy() if hasattr(other, 'copy') else copy.copy(other)
elif isinstance(other, Q) and not other:
_, args, kwargs = self.deconstruct()
return type(self)(*args, **kwargs)


obj = type(self)()
obj.connector = conn
obj.add(self, conn)
obj.add(other, conn)
return obj


def __or__(self, other):
return self._combine(other, self.OR)


def __and__(self, other):
return self._combine(other, self.AND)
.............

Ref。问实现