Question

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

Was it helpful?

Solution

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

OTHER TIPS

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)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top