Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

able to return nested dictionary using values? django

let's say if I have a model named Blog and this is how the value works

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

but let's say if I want to make the name into another dict and get such in return

[{'id': 1, 'blog': { 'name': 'Beatles Blog'}}]

is the above possible by using value or something similiar?

I know I can do something like which would work

[{'id': blog.pk, 'blog': {'name': blog.name}} for blog in blogs]

Thanks in advance for my curiosity

like image 209
Dora Avatar asked Aug 01 '18 23:08

Dora


People also ask

How to get Value in Nested dict?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

What is values and Values_list in Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.


1 Answers

This is not possible using values.

The method you suggested works well.

If you have a lot of extra fields on your model, and only need those two, a performance improvement would be to first load just the fields you need using values, then perform the list comprehension on them to reformat it as you specified.

This avoids unnecessarily querying the database for fields you do not need.

like image 139
roob Avatar answered Oct 23 '22 09:10

roob