9

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

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117

3 Answers3

17

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 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. https://docs.python.org/3/library/operator.html#operator.inv – falsetru Apr 19 '19 at 15:24
1

Thanks @falsetru.

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

~Q(Q)
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
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)))
pymen
  • 5,737
  • 44
  • 35