Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

django - How to combine select_related() and value()? (2016)

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

We know there is a values() 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',...}, ... }, ...]

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

This will return the following structure:

[{'author__id': 1, 'author__name': 'Dave'}, {...}]

If you need it in a nested structure you would have to transform it afterwards.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...