Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?
I want to serialize the following dictionary:
dictionary = { 'alfa': queryset1, 'beta': queryset2, }
I decided to do this using simplejson (comes with django). I extended simplejson.JSONEncoder the following way:
from django.utils import simplejson
from django.core import serializers
class HandleQuerySets(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("json", obj, ensure_ascii=False)
return simplejson.JSONEncoder.default(self, obj)
Then I do: simplejson.dumps( dictionary, cls=HandleQuerySets)
, but the returned dicionary looks like this:
{ "alfa": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]",
"beta": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]" }
Django-generated JSON is inserted to the dictionary as string, not JSON. What am I doing wrong?