Django equivalent of SQL not in

DjangoDjango Orm

Django Problem Overview


I have a very simple query: select * from tbl1 where title not in('asdasd', 'asdasd').

How do I translate that to Django? It's like I want the opposite of: Table.objects.filter(title__in=myListOfTitles)

Django Solutions


Solution 1 - Django

try using exclude

Table.objects.exclude(title__in=myListOfTitles)

Solution 2 - Django

Table.objects.exclude(title__in=myListOfTitles)

Solution 3 - Django

(this thread is old but still could be googled)

you can use models.Q with "~" as follows:

Table.objects.filter(~Q(title__in=myListOfTitles))

this method specially is helpful when you have multiple conditions.

Solution 4 - Django

Django provides two options.

exclude(<condition>)
filter(~Q(<condition>))

Method 2 using Q() method

>>> from django.db.models import Q
>>> queryset = User.objects.filter(~Q(id__lt=5))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - DjangoJamesOView Answer on Stackoverflow
Solution 2 - DjangoAlexey SavanovichView Answer on Stackoverflow
Solution 3 - DjangoomidView Answer on Stackoverflow
Solution 4 - DjangoMuhammad AbdullahView Answer on Stackoverflow