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

bash- picture bash- · Oct 4, 2011 · Viewed 68k times · Source

I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a .values set I get an exception:

'dict' object has no attribute '_meta'

This is my code:

queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = serializers.serialize('json', queryset, ensure_ascii=False)

Answer

Andre Gregori picture Andre Gregori · Aug 13, 2015

As other people have said, 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, you will need to pass in DjangoJSONEncoder. Thus:

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

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