Serializing objects containing django requests

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?

+4
source share
1 answer

The correct way to do this is:

 from django.utils import simplejson from django.core import serializers from django.db.models.query import QuerySet class HandleQuerySets(simplejson.JSONEncoder): """ simplejson.JSONEncoder extension: handle querysets """ def default(self, obj): if isinstance(obj, QuerySet): return serializers.serialize("python", obj, ensure_ascii=False) return simplejson.JSONEncoder.default(self, obj) 

Because serializers.serialize("json", [...]) returns a string; if you request a python serializer, you get dictionnary, and json encodes everything that is returned by your default encoder. See the json documentation for more details.

You will have to handle more types in your encoder (e.g. datetime objects), but you get the idea.

+10
source

All Articles