简体   繁体   English

Django objects.filter()values_list()vs __inin查询的python list comprehension

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

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()? 那么,如何使用values_list()? (to produce): (生产):

[1]

or is python list comprehension the 'way to go'? 或是python列表理解'走的路'?

Try l_magazines.values_list('id', flat=True) . 尝试l_magazines.values_list('id', flat=True) That returns a list of ids instead of a list of single id tuples. 这将返回一个id列表,而不是单个id元组列表。

One thing to note is that there is a difference in the behaviour of values/values_list from a list comprehension: 需要注意的一点是,值/ values_list与列表推导的行为存在差异:

  • values/values_list will yield the actual value stored in the field, that is, just the id (not the whole object) values / values_list将产生存储在字段中的实际值,即只是id(不是整个对象)
  • 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. 如果值是外键,并且您在模型中设置了适当的关系,则列表推导将为您提供外键引用的对象。

Choosing the wrong one will either result in unnecessary database hits, or unnecessary faffing around, depending on what you are trying to do. 选择错误的数据库会导致不必要的数据库命中,或者导致不必要的操作,具体取决于您尝试执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM