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 comparitive values, but is there a __ne/!=/<> (not equals?)

I want to filter out using a not equals:


    bool a;
    int x;

I want

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

The != is not correct syntax. I tried __ne, <>.

I ended up using:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)
12/19/2015 7:37:44 AM

Accepted Answer

Maybe Q objects could be of help for this problem. I've never used them but it seems they can be negated and combined much like normal python expressions.

Update: I Just tried it out, it seems to work pretty well:

>>> from myapp.models import Entry
>>> from django.db.models import Q

>>> Entry.objects.filter(~Q(id = 3))

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
2/8/2018 11:48:20 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow