Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a not equal in Django queryset filtering?

In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for

Model:     bool a;     int x; 

I want to do

results = Model.objects.exclude(a=True, x!=5) 

The != is not correct syntax. I also tried __ne.

I ended up using:

results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5) 
like image 593
MikeN Avatar asked Mar 26 '09 19:03

MikeN


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.

Can I filter a Queryset Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Is not Django filter?

In Django, “not in” means selecting the objects that contain the values that are not there in the given iterable. Basically, In Django, we don't have any filter with the name “not in”. So, to work in the same way as the “not in” filter works. We use exclude method with the “in” filter of Django.

How filter unique values Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.


2 Answers

Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x is 5. I believe this will do the trick:

results = Model.objects.filter(x=5).exclude(a=True) 

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

like image 22
d4nt Avatar answered Sep 20 '22 17:09

d4nt


You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

from myapp.models import Entry from django.db.models import Q  Entry.objects.filter(~Q(id=3)) 

will return all entries except the one(s) with 3 as their ID:

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...] 
like image 189
Dave Vogt Avatar answered Sep 19 '22 17:09

Dave Vogt