To do a “not equal” comparison in a Django queryset filter, you can use the __ne lookup type. For example:

MyModel.objects.filter(field__ne='value')

This will return all the MyModel instances where the field field is not equal to ‘value’.

You can also use the exclude() method to achieve the same result:

MyModel.objects.exclude(field='value')

Both of these examples will return the same queryset.

You can also use the != operator to achieve the same result:

MyModel.objects.filter(field != 'value')

This will also return all the MyModel instances where the field field is not equal to ‘value’.

Keep in mind that the __ne lookup and the != operator are not the same as the <> operator, which is a deprecated syntax for the “not equal” operator in Python. The <> operator is not supported in Django queryset filters.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply