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

0 votes

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:

Example:

Model:
    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)
Jul 3 in Python by kartik
• 19,630 points
124 views

1 answer to this question.

0 votes

Hello @kartik,

Try this code below:

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

Hope it helps!!

answered Jul 3 by Niroj
• 41,480 points

Related Questions In Python

0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12, 2019 in Python by Nymeria
• 3,520 points
3,773 views
+1 vote
1 answer
0 votes
1 answer

How do I perform query filtering in django templates?

Hello @KARTIK, Just add an extra template tag ...READ MORE

answered Jul 3 in Python by Niroj
• 41,480 points
72 views
0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27, 2019 in Python by rajesh
• 1,230 points
133 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
58 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
40 views
0 votes
1 answer

How to do a not equal in Django queryset filtering?

Hello @kartik, Your query appears to have a ...READ MORE

answered Jun 26 in Python by Niroj
• 41,480 points
109 views
+1 vote
1 answer

How do I create a slug in Django?

Hello @kartik, You will need to use the ...READ MORE

answered Jun 26 in Python by Niroj
• 41,480 points
45 views