问题描述
我再次问这个问题(),
I am asking this question again (it was asked back in 2009),
[{ 'author_id':3, ... }, ...]
我想要这样的结果:
[{ 'author':{'name':'dave',...}, ... }, ...]
在较新版本的Django中是否有所更改?
Has something changed in the newer versions of Django?
我想将查询集转换为列表和字典的组合,有可能吗?
I want to convert the query set into a combination of lists and dictionnaries, is it possible?
然后我将该对象并将其放入更大的对象中以进行序列化。这就是为什么我不想立即对其进行序列化的原因。
I will then take this object and place it into a bigger object to serialize it. It is the reason why I don't want to serialize it right away.
推荐答案
您可以通过无需使用(只有这些内容无需后续查找即可获取):
You can access related fields via values()
without the necessity to use select_related()
(only these will be fetched without subsequent lookup):
MyModel.objects.values('author__id', 'author__name')
这将返回以下结构:
[{'author__id': 1, 'author__name': 'Dave'}, {...}]
如果您需要嵌套结构,则必须对其进行转换。
If you need it in a nested structure you would have to transform it afterwards.
请注意,对于M2M关系,这将为每个M2M关系返回一个列表条目,因此可能不是期望的效果。
Note that for M2M relations, this returns one list entry per M2M relation, so probably not a desired effect. But for OneToOne/ForeignKey relations it works just fine.
编辑:对于M2M关系结合 values()
可以很好地工作。
for M2M relations annotate()
in combination with values()
works fine.
这篇关于如何结合select_related()和value()? (2016年)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!