简体   繁体   English

如何组合select_related()和value()?

[英]How to combine select_related() and value()?

We know there is a value() method of QuerySet, when there is a foreignkey (author, for example), it result like: 我们知道有一个QuerySet的value()方法,当有一个foreignkey(例如author)时,结果如下:

[{ 'author_id':3, ... }, ...]

I want a result like: 我想得到一个结果:

[{ 'author':{'name':'dave',...}, ... }, ...]

and I tried select_related, but values() won't show the detail of the foreignkey, what shall I do? 我尝试了select_related,但values()不会显示外键的详细信息,我该怎么办?

AFAIK, Django doesn't have builtin support for that. AFAIK,Django没有内置支持。 select_related never changes the outcome of a queryset, only the number of queries when you access related object. select_related永远不会更改查询集的结果,只会更改访问相关对象时的查询数。

You could use DjangoFullSerializers to get something that is similar to what you want. 你可以使用DjangoFullSerializers来获得类似于你想要的东西。

Implement the unicode method of each Model, and print it. 实现每个Model的unicode方法,并打印出来。

class Book(..):
    title = models.CharField(..)
    color = models.CharField(...)
    author = models.ForeignKey('Author')
    ...
    def __unicode__(self):
        return u"%s %s %s" %(title, color, author)

class Author(...):
    name = models.CharField(...)
    ...
    def __unicode__(self):
        return name

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

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