Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 401
Miguel Rosales Avatar asked Feb 24 '16 06:02

Miguel Rosales


People also ask

How can you combine multiple QuerySets in a view?

The SolutionThe Python union operator can be used to combine QuerySets that belong to the same model. You can also use the chain() method from the Itertools module, which allows you to combine two or more QuerySets from different models through concatenation.

What is the difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


1 Answers

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.

like image 185
Risadinha Avatar answered Sep 24 '22 23:09

Risadinha