How to convert a Django QuerySet to a list of dicts?

How to convert a Django QuerySet to a list of dicts? I did not find an answer to this, so I wonder if I am missing some common helper function that everyone uses.

+77
python django
Oct 18 '11 at 17:52
source share
6 answers

Use the .values() method:

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

Note: the result is a QuerySet , which basically behaves like a list, but is not really an instance of list . Use list(Blog.objects.values(…)) if you really need an instance of list .

+107
Oct 18 2018-11-18T00:
source share

The .values() method will return you a result of type ValuesQuerySet , which you usually need in most cases.

But if you want, you can turn ValuesQuerySet into your own Python list using Python list comprehension, as shown in the example below.

 result = Blog.objects.values() # return ValuesQuerySet object list_result = [entry for entry in result] # converts ValuesQuerySet into Python list return list_result 

I find this helps if you write unit tests and have to argue that the expected return value of the function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. a dictionary).

 actual_result = some_function() expected_result = { # dictionary content here ... } assert expected_result == actual_result 
+22
Sep 08 '14 at 5:51 on
source share

If you need native data types for any reason (like JSON serialization), this is my quick "n" dirty way to do this:

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

As you can see, building a dict inside a list is not really DRY, so if someone knows a better way ...

+6
Mar 25 '17 at 10:33
source share

You do not determine exactly what dictionaries should look like, but most likely you mean QuerySet.values() . From django official documentation :

Returns a subclass of ValuesQuerySet - a QuerySet , which returns dictionaries when using objects as an iterative rather than an instance of the model.

Each of these dictionaries is an object with keys corresponding to the names of the attributes of the model objects.

+3
Oct 18 '11 at 17:58
source share

You can use the values() method in the dict file that you got from the field of the Django model on which you make requests, and then you can easily access each field by the index value.

Call it like this:

 myList = dictOfSomeData.values() itemNumberThree = myList[2] #If there a value in that index off course... 
0
Feb 20 '16 at 9:27
source share

Simply put, list(yourQuerySet) .

0
Jan 24 '19 at 12:10
source share



All Articles