Last active
August 29, 2015 13:59
-
-
Save maxvyaznikov/10526923 to your computer and use it in GitHub Desktop.
Make Django Models and QuerySets json serializable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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