Django provides tools for serializing queries (django.core.serializers), but what about serializing queries that live 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 as follows:
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 into the dictionary as a string, not JSON. What am I doing wrong?
source share