I have a complex Q object created dynamically. How do I negate the Q object so that it can be used in filter()
instead of exclude()
?
Negate a Q object in Django
Use ~
operator:
complex_condition = ~Q(....)
According to Complex lookups with Q objects:
Q
objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query
Thanks @falsetru.
What I was trying was running the Q object through another negated Q object:
~Q(Q)
If you cant use ~
operator like ~Q(**filters) - use operator.inv(q)
import operator
negated_q = operator.inv(query)
Usage Example
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)))
© 2022 - 2024 — McMap. All rights reserved.
operator.not_(x)
is similar tonot x
. Useoperator.inv(x)
oroeprator.invert
to mean~x
. Sorry for late (too late) reply. docs.python.org/3/library/operator.html#operator.inv – Brazell