7

我有一个动态创建的复杂 Q 对象。如何否定 Q 对象,以便它可以用于filter()代替exclude()

4

3 回答 3

13

使用~运算符:

complex_condition = ~Q(....)

根据带有 Q 对象的复杂查找

Q对象可以使用~ 操作符取反,允许结合普通查询和取反(NOT)查询的组合查找

于 2014-02-07T05:21:36.320 回答
1

谢谢@falsetru。

我正在尝试通过另一个否定的 Q 对象运行 Q 对象:

~Q(Q)
于 2014-02-07T05:37:05.257 回答
0

如果你不能使用~像 ~Q(**filters) 这样的运算符 - 使用operator.inv(q)

import operator
negated_q = operator.inv(query)

使用示例

q_filter = Q(user__profile_id=777)
>> (AND: ('user__profile_id', 777))
negated_q_filter = operator.inv(q_filter)
>> (NOT (AND: ('user__profile_id', 777)))
于 2020-12-14T09:19:37.760 回答