python - Serializing objects containing django querysets -


django provides tools serialize querysets (django.core.serializers), serializing querysets living inside other objects (like dictionaries)?

i want serialize following dictionary:

dictionary = { 'alfa': queryset1, 'beta': queryset2, }  

i decided using simplejson (comes django). extended simplejson.jsonencoder following way:

from django.utils import simplejson 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 do: simplejson.dumps( dictionary, cls=handlequerysets), returned dicionary looks this:

{ "alfa": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]",   "beta": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]" } 

django-generated json inserted dictionary string, not json. doing wrong?

the correct way be:

from django.utils import simplejson django.core import serializers 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 string ; if ask python serializer, dictionnary, , json encodes whatever returned encoder's default method. @ json documentation details.

you have handle more types in encoder class (such datetime objects), idea.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -