filter() values_list()和python列表理解在查询中

时间:2022-09-01 01:35:43

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

我有一个关于Django queryset过滤的怪癖(?)

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列表理解是“前进之路”吗?

2 个解决方案

#1


58  

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”,平= True)。它返回一个id列表,而不是单个id元组列表。

#2


2  

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

选择错误的选项会导致不必要的数据库访问,或者是不必要的浪费,这取决于你想要做什么。

#1


58  

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”,平= True)。它返回一个id列表,而不是单个id元组列表。

#2


2  

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

选择错误的选项会导致不必要的数据库访问,或者是不必要的浪费,这取决于你想要做什么。