Skip to content

Instantly share code, notes, and snippets.

@rvause
Last active December 16, 2015 20:49
Show Gist options
  • Select an option

  • Save rvause/5494989 to your computer and use it in GitHub Desktop.

Select an option

Save rvause/5494989 to your computer and use it in GitHub Desktop.
A generic way to serialize model instances into something you can just json.dumps
from django.db.models.fields import FieldDoesNotExist
class SerializeMixin(object):
def serialize(self, recursive=True):
data = {}
for field in self.__class__._meta.get_all_field_names():
try:
self.__class__._meta.get_field(field)
data[field] = self.serializable_value(field)
except FieldDoesNotExist:
if recursive:
try:
related = getattr(self, field)
data[field] = []
for obj in related.all():
data[field].append(obj.serialize())
except AttributeError:
pass
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment