Skip to content

Instantly share code, notes, and snippets.

@maxvyaznikov
Last active August 29, 2015 13:59
Show Gist options
  • Save maxvyaznikov/10526923 to your computer and use it in GitHub Desktop.
Save maxvyaznikov/10526923 to your computer and use it in GitHub Desktop.
Make Django Models and QuerySets json serializable
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model
from django.db.models.query import QuerySet
from django.forms import model_to_dict
class ExtendedDjangoJSONEncoder(DjangoJSONEncoder):
def default(self, o):
if hasattr(o, 'to_dict'):
return o.to_dict()
elif issubclass(o.__class__, Model):
return model_to_dict(o)
elif issubclass(o.__class__, QuerySet):
return [self.default(m) for m in o]
else:
return super(ExtendedDjangoJSONEncoder, self).default(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment