Continuation
Continuation

Reputation: 13040

Django: does the ORM support the SQL "IN" operator?

Does the Django ORM support the SQL IN operator? Something like:

SELECT *
FROM user
WHERE id IN (1, 5, 34, 567, 229)

How do I use the Django ORM to make a query like that?

Thanks.

Upvotes: 37

Views: 27852

Answers (3)

Ruc Van
Ruc Van

Reputation: 71

Beside that, Django ORM also support for Sub-Query:

For example:

from django.db.models import Subquery
users = User.objects.all()
UserParent.objects.filter(user_id__in=Subquery(users.values('id')))

Upvotes: 7

gskluzacek
gskluzacek

Reputation: 105

as Yuji indicates above <field_name>__in=[<list_of_values>] is translated to the following SQL:

WHERE <field_name> IN (<list_of_values>)

you can find the complete reference of django SQL WHERE operators under the Field lookups section of the following Django API document.

https://docs.djangoproject.com/en/1.9/ref/models/querysets/

Upvotes: 0

in

User.objects.filter(id__in=[1, 5, 34, 567, 229])

print _.query
SELECT <fields> FROM "auth_user" WHERE "auth_user"."id" IN (1, 5, 34, 567, 229)

Upvotes: 63

Related Questions