如何结合select_related()和value()? (2016年) [英] How to combine select_related() and value()? (2016)

查看:65
本文介绍了如何结合select_related()和value()? (2016年)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我再次问这个问题(它是在2009年问到的),

I am asking this question again (it was asked back in 2009),


我们知道QuerySet有 values()方法,当有
外键(例如作者)时,结果如下:

We know there is a values() method of QuerySet, when there is a foreignkey (author, for example), it result like:

[{ '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.

推荐答案

您可以通过 values() 无需使用 select_related() (只有这些内容无需后续查找即可获取):

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关系 annotate() 结合 values()可以很好地工作。

for M2M relations annotate() in combination with values() works fine.

这篇关于如何结合select_related()和value()? (2016年)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆