HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythondjangoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfilteringequalnotquerysetdjango

Problem

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)

Solution

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:

[, , , ...]

Code Snippets

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>, ...]

Context

Stack Overflow Q#687295, score: 1139

Revisions (0)

No revisions yet.