Django objects.filter() values_list() vs python list comprehension for __in 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4812035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:38:14  来源:igfitidea点击:

Django objects.filter() values_list() vs python list comprehension for __in query

pythondjangodjango-modelsdjango-queryset

提问by Daryl

I have a quirk(?) with Django queryset filtering:

我有一个 Django 查询集过滤的怪癖(?):

ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id'))
Out[0]: []

or

或者

ipdb> MagazineIssue.objects.filter(id__in=[l_magazine.id for l_magazine in l_magazines])
Out[0]: [<MagazineIssue: Architecture Australia, Jan 1995 (#1)>]

and

ipdb> l_magazines.values_list('id')
Out[0]: [(1,)]
ipdb> [l_magazine.id for l_magazine in l_magazines]
Out[0]: [1]

so, how to use values_list()? (to produce):

那么,如何使用 values_list()?(生产):

[1]

or is python list comprehension the 'way to go'?

还是python列表理解是“要走的路”?

采纳答案by Cloud Artisans

Try l_magazines.values_list('id', flat=True). That returns a list of ids instead of a list of single id tuples.

试试l_magazines.values_list('id', flat=True)。这将返回一个 id 列表而不是单个 id 元组列表。

回答by Marcin

One thing to note is that there is a difference in the behaviour of values/values_list from a list comprehension:

需要注意的一件事是, values/values_list 的行为与列表理解有所不同:

  • values/values_list will yield the actual value stored in the field, that is, just the id (not the whole object)
  • if the value is a foreign key, and you have the appropriate relations set up in your model, the list comprehension will give you the object referred to by the foreign key.
  • values/values_list 将产生存储在该字段中的实际值,即仅 id(而不是整个对象)
  • 如果该值是一个外键,并且您在模型中设置了适当的关系,则列表理解将为您提供外键引用的对象。

Choosing the wrong one will either result in unnecessary database hits, or unnecessary faffing around, depending on what you are trying to do.

选择错误的将导致不必要的数据库命中,或不必要的胡闹,这取决于您要做什么。