How do I convert a Django QuerySet into list of dicts?

PythonDjango

Python Problem Overview


How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.

Python Solutions


Solution 1 - Python

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 mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

Solution 2 - Python

The .values() method will return you a result of type ValuesQuerySet which is typically what you need in most cases.

But if you wish, you could turn ValuesQuerySet into a native Python list using Python list comprehension as illustrated 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 the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. dictionary).

actual_result = some_function()
expected_result = {
    # dictionary content here ...
}
assert expected_result == actual_result

Solution 3 - Python

If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:

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

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

Solution 4 - Python

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

Solution 5 - Python

You do not exactly define what the dictionaries should look like, but most likely you are referring to QuerySet.values(). From the official django documentation:

> Returns a ValuesQuerySet — a QuerySet subclass that returns > dictionaries when used as an iterable, rather than model-instance > objects. > > Each of those dictionaries represents an object, with the keys > corresponding to the attribute names of model objects.

Solution 6 - Python

You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

Solution 7 - Python

You can use the values() method on the dict you got from the Django model field you make the queries on and then you can easily access each field by a index value.

Call it like this -

myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...

Solution 8 - Python

You could define a function using model_to_dict as follows:

def queryset_to_list(qs,fields=None, exclude=None):
    my_list=[]
    for x in qs:
        my_list.append(model_to_dict(x,fields=fields,exclude=exclude))
    return my_list

Suppose your Model has following fields

id
name
email

Run following commands in django shell

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'[email protected]'},{'id':2, 'name':'xyz', 'email':'[email protected]'}]

Say you want only id and name in the list of queryset dictionary

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]

Similarly you can exclude fields in your output.

Solution 9 - Python

If you already have a query set you just use the list function to turn it into a list of dicts, eg:

list(MyModel.objects.values())

Solution 10 - Python

im a newbie in python and i love @David Wolever answer

user = Blog.objects.all()
user = list(user.values("username", "id"))

in my case i use this to print username

user = Blog.objects.all()
user = list(user.values("username"))
name = []
for i in user:
    name.append(i["username"])
print(name)
# ["joe", "karen", "stuf"]

Solution 11 - Python

Simply put list(yourQuerySet).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMridang AgarwallaView Question on Stackoverflow
Solution 1 - PythonDavid WoleverView Answer on Stackoverflow
Solution 2 - PythonArthur RimbunView Answer on Stackoverflow
Solution 3 - PythonSemmelView Answer on Stackoverflow
Solution 4 - PythonSaurabh Chandra PatelView Answer on Stackoverflow
Solution 5 - PythonBernhard VallantView Answer on Stackoverflow
Solution 6 - PythongaozhidfView Answer on Stackoverflow
Solution 7 - PythonIdo MagorView Answer on Stackoverflow
Solution 8 - PythonABNView Answer on Stackoverflow
Solution 9 - PythonMark BView Answer on Stackoverflow
Solution 10 - PythonBitchBarkView Answer on Stackoverflow
Solution 11 - PythonMiguel de MatosView Answer on Stackoverflow