Search code examples
pythondjangodjango-q

Negate a Q object in Django


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


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