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 every
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
— aQuerySet
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.
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)
Simply put list(yourQuerySet)
.