Django query negation

Daniel Gollás picture Daniel Gollás · Feb 3, 2010 · Viewed 28.4k times · Source

I know how to build filters and Q objects in django, but I don't know how to negate the operators that the API provides, for example for the contains operator I would like something like notcontains.

e.g.

q=Q(name__notcontains="SomeString")

This would get me all objects whose name do not contain "SomeString".

Is there some syntax that I'm missing?

Thankyou.

Answer

Ludwik Trammer picture Ludwik Trammer · Feb 3, 2010

You can use exclude() in place of filter():

Entry.objects.exclude(name__contains="SomeString")

("give me all entries EXCEPT those with names containing "SomeString")

And when dealing with Q object you can use "~" symbol before Q object to represent negation. For example the following statement means "give me all Entries with names containing "Elephant", but NOT containing "SomeString":

Entry.objects.filter(Q(name__contains="Elephant") & ~Q(name__contains="SomeString"))

In some cases you may want to use both methods:

Entry.objects.exclude(Q(name__contains="Elephant") & ~Q(name__contains="SomeString"))

("give me all entries, EXCEPT those with names containing "Elephant", but NOT containing "SomeString")