开发者

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

开发者 https://www.devze.com 2023-02-21 05:19 出处:网络
Does the Django ORM support the SQL IN 开发者_如何学JAVAoperator? Something like: SELECT * FROM user

Does the Django ORM support the SQL IN 开发者_如何学JAVAoperator? 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.


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)


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


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消