Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query negation

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.

like image 508
Daniel Gollás Avatar asked Feb 03 '10 19:02

Daniel Gollás


People also ask

How do you say not equal to in Django?

To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.

What is f() in Django?

F() can be used to create dynamic fields on your models by combining different fields with arithmetic: company = Company. objects. annotate( chairs_needed=F('num_employees') - F('num_chairs')) If the fields that you're combining are of different types you'll need to tell Django what kind of field will be returned.

What is Django Q?

Django Q is a native Django task queue, scheduler and worker application using Python multiprocessing.

How do I use Django ORM?

To do so, open the Django shell to run the query. You might be wonder how Django ORM makes our queries executed or what the corresponding query of the code we are writing. It is quite simple to get the SQL query, we need to use the str() and pass the queryset object along with query.


1 Answers

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")

like image 137
Ludwik Trammer Avatar answered Sep 21 '22 09:09

Ludwik Trammer