[英]How can I filter a Django query with a list of values?
I'm sure this is a trivial operation, but I can't figure out how it's done. 我确信这是一个微不足道的操作,但我无法弄清楚它是如何完成的。
There's got to be something smarter than this: 必须有比这更聪明的东西:
ids = [1, 3, 6, 7, 9]
for id in ids:
MyModel.objects.filter(pk=id)
I'm looking to get them all in one query with something like: 我希望通过以下方式将它们全部放入一个查询中:
MyModel.objects.filter(pk=[1, 3, 6, 7, 9])
How can I filter a Django query with a list of values? 如何使用值列表过滤Django查询?
从Django文档 :
Blog.objects.filter(pk__in=[1, 4, 7])
When you have list of items and you want to check the possible values from the list then you can't use =
. 当您有项目列表并且想要从列表中检查可能的值时,则不能使用
=
。
The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9]
which is not true. sql查询将类似于
SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9]
,这不是真的。 You have to use in
operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9)
for that Django provide __in
operator. 你必须
in
运算符中使用这个,所以你的查询将像( SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9)
__in
SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9)
那样Django提供__in
运算符。
From the Django documentation : 从Django文档 :
Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
Blog.objects.in_bulk([])
{}
Blog.objects.in_bulk()
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}
Blog.objects.in_bulk(['beatles_blog'], field_name='slug')
{'beatles_blog': <Blog: Beatles Blog>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.