Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django format a request in a list

I need help to format a response of a django request, This is a exemple :

With a model like this:

Book(models):
    name = string
    author = string
    release = date

A request :
Book.objects.filter(author='Hergé').value('name')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I got :
[{'name':'Tintin au Tibet'}, {'name':'Tintin au Congo'}, {'name':'Tintin chez les Picarros'}]

I want this :
['Tintin au Tibet','Tintin au Congo','Tintin chez les Picarros']

My question:
How to I get what I want by changing only the request ?

>Solution :

You can work with .values_list(…) [Django-doc]:

Book.objects.filter(author='Hergé').values_list('name', flat=True)

But usually it is not a good idea to use .values(…) or .values_list(…) to retrieve data, not even to serialize: it erodes the model layer, and thus will prevent fetching related objects, obtaining the display name, etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading