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, 2020 in Python by kartik
• 37,510 points
1,798 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, 2020 by Niroj
• 82,720 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
7,837 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, 2020 in Python by Niroj
• 82,720 points
460 views
+1 vote
1 answer

How do I return JSON without using a template in Django?

Hello @kartik, In the case of the JSON ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,720 points
2,449 views
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, 2020 in Python by Niroj
• 82,720 points
3,410 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, 2020 in Python by Niroj
• 82,720 points
790 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, 2020 in Python by Niroj
• 82,720 points
323 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, 2020 in Python by Niroj
• 82,720 points
5,947 views
0 votes
1 answer

How can I do not equal in Django queryset filtering?

Hello @kartik, You can use Q objects for this. They ...READ MORE

answered Nov 17, 2020 in Python by Niroj
• 82,720 points
95 views