goodjson.py: from django.core.serializers.json import DateTimeAwareJSONEncoder from django.core import serializers from django.db.models.query import QuerySet from django.db.models import Model from django.utils import simplejson from django.core.serializers.python import Serializer as PythonSerializer#, Deserializer as PythonDeserializer from django.utils.encoding import smart_unicode try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class ModelAwareJSONEncoder(DateTimeAwareJSONEncoder): def __init__(self,select_related=False,include_unicode=False,**options): super(ModelAwareJSONEncoder,self).__init__(**options) self.select_related = select_related self.include_unicode = include_unicode def default(self, o): if self.select_related: serializer_name = 'goodpython' else: serializer_name = 'python' if isinstance(o, QuerySet): serializer = serializers.get_serializer(serializer_name)() serializer.include_unicode = self.include_unicode return serializer.serialize(o) if isinstance(o, Model): serializer = serializers.get_serializer(serializer_name)() serializer.include_unicode = self.include_unicode return serializer.serialize([o])[0] else: return super(ModelAwareJSONEncoder, self).default(o) class Serializer(PythonSerializer): def serialize(self, object, **options): return simplejson.dumps(object, cls=ModelAwareJSONEncoder, **options) goodpython.py: from django.core.serializers.json import DateTimeAwareJSONEncoder from django.core import serializers from django.db.models.query import QuerySet from django.db.models import Model from django.utils import simplejson from django.core.serializers.python import Serializer as PythonSerializer#, Deserializer as PythonDeserializer from django.utils.encoding import smart_unicode from django.template.defaultfilters import force_escape, escapejs, mark_safe from core.libs.htmlfield import HtmlField try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class Serializer(PythonSerializer): def end_object(self, obj): fields = self._current if hasattr(self,'include_unicode') and self.include_unicode: fields.update({'__unicode__': unicode(obj)}) self.objects.append({ "model" : smart_unicode(obj._meta), "pk" : smart_unicode(obj._get_pk_val(), strings_only=True), "fields" : fields }) self._current = None def handle_fk_field(self, obj, field): related = getattr(obj, field.name) self._current[field.name] = self.serialize_related(related) def handle_m2m_field(self, obj, field): self._current[field.name] = [self.serialize_related(related) for related in getattr(obj, field.name).iterator()] def handle_field(self, obj, field): ''' The std. serialization is not suitable for the fields containing HTML. If such JSON is being output inside an inline