Ali
Ali

Reputation: 3666

Django equivalent of SQL not in

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)

Upvotes: 107

Views: 100355

Answers (5)

Narek
Narek

Reputation: 41

You can also use exclude:

Table.objects.exclude(title__in=myListOfTitles)

You can also combine filter and exclude

Table.objects.filter(title__in=includingTitles).exclude(title__in=excludingTitles)

Upvotes: 0

Muhammad Abdullah
Muhammad Abdullah

Reputation: 483

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))

Upvotes: 3

omid
omid

Reputation: 842

(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.

Upvotes: 44

Alexey Savanovich
Alexey Savanovich

Reputation: 1903

Table.objects.exclude(title__in=myListOfTitles)

Upvotes: 29

JamesO
JamesO

Reputation: 25936

try using exclude

Table.objects.exclude(title__in=myListOfTitles)

Upvotes: 207

Related Questions