957

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)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
MikeN
  • 45,039
  • 49
  • 151
  • 227
  • 91
    Would results = Model.objects.exclude(a=true).filter(x=5) have worked? – hughdbrown Jul 27 '09 at 21:00
  • 7
    @hughdbrown. No. Your query excludes all `a=true` first and then applies the `x=5` filter on the remaining. The intended query required only those with `a=true` and `x!=5`. The difference being that all those with `a=true` and `x=5` are also filtered out. – Mitchell van Zuylen Feb 15 '18 at 12:58

17 Answers17

1066

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>, ...]
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Dave Vogt
  • 18,600
  • 7
  • 42
  • 54
  • 48
    Is there any reason to do `Entry.objects.filter(~Q(id=3))` rather than `Entry.objects.exclude(id=3)`? – Bob Whitelock Dec 14 '20 at 11:46
  • 2
    I suppose its use is conditional on the scenario, but Q objects allow for more complex queries. For example, you could string together the `~Q` query with other ones as well. https://docs.djangoproject.com/en/3.2/topics/db/queries/#complex-lookups-with-q-objects – jeremy_lord Sep 04 '21 at 05:42
  • 3
    @BobWhitelock: It's just a simple snippet for the question. In real world, much cases we have to use this. For example: EXCLUDE(A=1 and B__not=2); use extra .exclude is not right. – anhtran Sep 22 '21 at 09:48
  • 1
    This makes sense... If you were to do a filtering in an annotation or aggregation, this would come in handy. – Chymdy Dec 03 '21 at 08:51
  • A typical use is to know if an object with a different parameter exists: `Entry.objects.filter(~Q(param="good")).exists()` – echefede Jun 10 '22 at 22:18
  • 1
    @echefede, exclude would also work in such a scenario – emanuel sanga Aug 07 '22 at 15:44
793

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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
d4nt
  • 15,475
  • 9
  • 42
  • 51
  • 2
    @d4nt: I may be wrong, but I think the query should be `results = Model.objects.filter(a=true).exclude(x=5)` – Taranjeet Sep 02 '15 at 14:59
  • 1
    @Taranjeet: I think you misread the original query. d4nt's version is correct, because OP wanted to exclude(a=True) and negate the exclusion of x=5 (i.e. include it). – Chuck Sep 16 '15 at 20:55
  • 6
    I think this is wrong because an instance (x=4, a=false) would be wrongly excluded. – RemcoGerlich Nov 17 '15 at 14:14
  • Just to say, the order matters so `objects.exclude(**filter1).filter(**filter2)` gives different results from `objects.filter(**filter1).exclude(**filter2)`, while ~Q will always get correct negation inside `objects.filter(**filter_with_Q)` – danius Jan 06 '16 at 12:15
  • 4
    @danigosa That doesn't seem right. I just tried this myself, and the order of `exclude` and `filter` calls didn't make any meaningful difference. The order of the conditions in the `WHERE` clause changes, but how does that matter? – coredumperror Apr 07 '16 at 19:51
  • 4
    @danigosa order of exclude and filter doesn't matter. – EralpB Sep 05 '17 at 07:29
  • This may fail if you are filtering on related object fields. – dhill Jun 07 '19 at 14:48
  • 1
    This answer is wrong. "you want to exclude all rows where x is not 5" - No, the asker wants to exclude rows where (x is not 5 **AND** a is True). !(x != 5 AND a) iff. (!(x != 5) OR !a) [by De Morgan] iff. (x == 5 OR !a) [ by double negation] But this solution provides all rows where (x == 5 AND !a) Which is of course different in the cases where (x == 5 AND a) or when (x !=5 AND !a) – talz Jan 26 '21 at 10:43
167

the field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range

date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second

isnull
regex
iregex

I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you'll get exactly what you need for just about any possible query.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • thanks this is awesome . i used some thing like this `tg=Tag.objects.filter(user=request.user).exclude(name__regex=r'^(public|url)$')` and it works. – suhailvs Sep 11 '13 at 07:12
  • 1
    @suhail, please mind that not all databases support that regex syntax :) – Anoyz Jul 12 '16 at 10:44
  • 3
    i in `icontains`, `iexact` and similar stands for "ignore case sensitivity". It is not for "inverse". – Ivy Growing May 06 '17 at 14:59
  • It is worth noting that when you are using `exclude()` with multiple terms, you may want to compose the proposition with the `OR` operator, e.g. `exclude(Q(field1__queryop1=value1) | Q(field2__queryop2=value2))` in order to exclude the results under both conditions. – clapas Aug 25 '17 at 10:30
158

There are three options:

  1. Chain exclude and filter

    results = Model.objects.exclude(a=True).filter(x=5)
    
  2. Use Q() objects and the ~ operator

    from django.db.models import Q
    object_list = QuerySet.filter(~Q(a=True), x=5)
    
  3. Register a custom lookup function

    from django.db.models import Lookup
    from django.db.models import Field
    
    @Field.register_lookup
    class NotEqual(Lookup):
        lookup_name = 'ne'
    
        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return '%s <> %s' % (lhs, rhs), params
    

    Which can the be used as usual:

    results = Model.objects.exclude(a=True, x__ne=5)
    
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
ilse2005
  • 11,189
  • 5
  • 51
  • 75
  • 1
    object_list = QuerySet.filter(~Q(a=True), x=5) : Remember to keep all the other conditions not containing Q after those containing Q. – Bhumi Singhal Jun 06 '17 at 12:28
  • 1
    @MichaelHoffmann : A)you will then filter on a smaller set of data after exclusion using ~Q so is more efficient. B) probably the sequencing the other way around does not work .. dun know .. dun remember! – Bhumi Singhal Feb 28 '19 at 08:48
  • 2
    wonder if there is a performance difference in 1 vs 2 – Anupam Aug 12 '20 at 23:17
  • 1
    NOTE: the `exclude` will add something to the WHERE clause, so it can be pretty efficient. See https://docs.djangoproject.com/en/3.2/ref/models/querysets/#exclude. @Anupam – dfrankow Jun 14 '21 at 17:50
121

It's easy to create a custom lookup, there's an __ne lookup example in Django's official documentation.

You need to create the lookup itself first:

from django.db.models import Lookup

class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params

Then you need to register it:

from django.db.models import Field
Field.register_lookup(NotEqual)

And now you can use the __ne lookup in your queries like this:

results = Model.objects.exclude(a=True, x__ne=5)
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Dmitrii Mikhailov
  • 5,053
  • 7
  • 43
  • 69
55

While you can filter Models with =, __gt, __gte, __lt, __lte, you cannot use ne or !=. However, you can achieve better filtering using the Q object.

You can avoid chaining QuerySet.filter() and QuerySet.exclude(), and use this:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Dami
  • 920
  • 6
  • 12
30

Pending design decision. Meanwhile, use exclude()

The Django issue tracker has the remarkable entry #5763, titled "Queryset doesn't have a "not equal" filter operator". It is remarkable because (as of April 2016) it was "opened 9 years ago" (in the Django stone age), "closed 4 years ago", and "last changed 5 months ago".

Read through the discussion, it is interesting. Basically, some people argue __ne should be added while others say exclude() is clearer and hence __ne should not be added.

(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have != because it has == and not already...)

Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
25

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)
Philip John
  • 5,275
  • 10
  • 43
  • 68
jincy mariam
  • 589
  • 6
  • 7
  • 3
    How's this different from [@d4nt's answer](https://stackoverflow.com/a/4139956) left 8 years before yours and [@outoftime's answer](https://stackoverflow.com/a/32778343) made 3 years before this one? – Boris Verkhovskiy Nov 12 '20 at 07:10
16

You should use filter and exclude like this

results = Model.objects.exclude(a=true).filter(x=5)
outoftime
  • 715
  • 7
  • 21
  • 2
    How's this different from [@d4nt's answer](https://stackoverflow.com/a/4139956) made 5 years before yours? – Boris Verkhovskiy Nov 12 '20 at 07:10
  • @BorisVerkhovskiy "edited Nov 12, 2020 at 7:03" you should be color blind or something. – outoftime Nov 18 '22 at 13:08
  • 1
    If you click on "edited", you can see exactly what the person who edited the answer (it was me) changed, and you'll see that I fixed spelling mistakes and added links to documentation, otherwise the answer is the same as it was when it was posted in 2010. – Boris Verkhovskiy Nov 18 '22 at 14:05
10

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.

tzot
  • 92,761
  • 29
  • 141
  • 204
Milad Khodabandehloo
  • 1,907
  • 1
  • 14
  • 24
  • Please check the edit; using “and” in `Q(a=True) and ~Q(x=5)` would evaluate to `~Q(x=5)` as arguments to `.exclude`. Please read: https://docs.python.org/3/reference/expressions.html#boolean-operations and https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations . – tzot Oct 11 '19 at 08:56
8

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)
Gerard
  • 124
  • 1
  • 4
8

Django-model-values (disclosure: author) provides an implementation of the NotEqual lookup, as in this answer. It also provides syntactic support for it:

from model_values import F
Model.objects.exclude(F.x != 5, a=True)
A. Coady
  • 54,452
  • 8
  • 34
  • 40
7

results = Model.objects.filter(a = True).exclude(x = 5)
Generetes this sql:
select * from tablex where a != 0 and x !=5
The sql depends on how your True/False field is represented, and the database engine. The django code is all you need though.
M. Dasn
  • 133
  • 1
  • 3
6

This should work

results = Model.objects.filter(x=5).exclude(a=True)
Yusuf Ganiyu
  • 842
  • 9
  • 8
  • This is the exact same code as [@d4nt's answer](https://stackoverflow.com/a/4139956) from 12 years ago, [@outoftime's](https://stackoverflow.com/a/32778343) answer from 7 years ago and [@jincymariam's answer](https://stackoverflow.com/a/51303588) from 4 years ago. – Boris Verkhovskiy Nov 18 '22 at 14:13
5

The last bit of code will exclude all objects where x!=5 and a is True. Try this:

results = Model.objects.filter(a=False, x=5)

Remember, the = sign in the above line is assigning False to the parameter a and the number 5 to the parameter x. It's not checking for equality. Thus, there isn't really any way to use the != symbol in a query call.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
2

Watch out for lots of incorrect answers to this question!

Gerard's logic is correct, though it will return a list rather than a queryset (which might not matter).

If you need a queryset, use Q:

from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))
Mark Bailey
  • 1,617
  • 1
  • 7
  • 13
  • "Gerard's [...] will return a list rather than a queryset" - that's not true. it returns a queryset. And your answer is the same as the accepted answer. – Boris Verkhovskiy Nov 12 '20 at 06:57
1

If we need to exclude/negate based on the sub queryset we can use,

Conditional filter:

When a conditional expression returns a boolean value, it is possible to use it directly in filters. Here non_unique_account_type returns a boolean value. But, still, we can use it in the filter.

>>> non_unique_account_type = Client.objects.filter(
...     account_type=OuterRef('account_type'),
... ).exclude(pk=OuterRef('pk')).values('pk')
>>> Client.objects.filter(~Exists(non_unique_account_type))

In the SQL terms, it evaluates to:

SELECT * FROM client c0
WHERE NOT EXISTS (
  SELECT c1.id
  FROM client c1
  WHERE c1.account_type = c0.account_type AND NOT c1.id = c0.id
)
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16