问题:如何使用值列表过滤Django查询?

我敢肯定这是一个微不足道的操作,但是我不知道它是如何完成的。

肯定有比这更聪明的东西:

ids = [1, 3, 6, 7, 9]

for id in ids:
    MyModel.objects.filter(pk=id)

我正在寻找将它们全部添加到一个查询中,例如:

MyModel.objects.filter(pk=[1, 3, 6, 7, 9])

如何使用值列表过滤Django查询?

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?


回答 0

Django文档中

Blog.objects.filter(pk__in=[1, 4, 7])

From the Django documentation:

Blog.objects.filter(pk__in=[1, 4, 7])

回答 1

如果您有项目列表,并且想要从列表中检查可能的值,则不能使用=

sql查询就像SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9]是不正确的。您必须为此使用in运算符,因此您的查询将类似于SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9)Django提供的__in运算符。

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


回答 2

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

From the Django documentation:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。