Privacy Policy
Snippets index

  How to serialize Django queryset.values() into json?

Django's serializers can't handle a ValuesQuerySet.

However, you can serialize by using a standard json.dumps() and transforming your ValuesQuerySet to a list by using list().

If your set includes Django fields such as Decimals or UUIDs, you will need to pass in DjangoJSONEncoder.

Thus:

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

queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = json.dumps(list(queryset), cls=DjangoJSONEncoder)

return HttpResponse(serialized_q, content_type='application/json')

Or just convert the ValuesQuerySet into a Python list, so you can further manipulate it:

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

queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
data = list(queryset)

...

return JsonResponse(data, safe=False)

References: