How to combine select_related() and value()?

2019-02-18 03:24发布

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

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

2条回答
一纸荒年 Trace。
2楼-- · 2019-02-18 03:35

AFAIK, Django doesn't have builtin support for that. select_related never changes the outcome of a queryset, only the number of queries when you access related object.

You could use DjangoFullSerializers to get something that is similar to what you want.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-18 03:45

Implement the unicode method of each Model, and print it.

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
查看更多
登录 后发表回答