Negate a Q object in Django
Asked Answered
M

3

10

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()?

Magistery answered 7/2, 2014 at 5:21 Comment(0)
B
19

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

Brazell answered 7/2, 2014 at 5:21 Comment(1)
@ATOzTOA, operator.not_(x) is similar to not x. Use operator.inv(x) or oeprator.invert to mean ~x. Sorry for late (too late) reply. docs.python.org/3/library/operator.html#operator.invBrazell
M
1

Thanks @falsetru.

What I was trying was running the Q object through another negated Q object:

~Q(Q)
Magistery answered 7/2, 2014 at 5:37 Comment(0)
S
0

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)))
Swath answered 14/12, 2020 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.