Skip to content

Instantly share code, notes, and snippets.

@foxbunny
Last active December 14, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxbunny/3f2cc3d5fbfb7282b1e6 to your computer and use it in GitHub Desktop.
Save foxbunny/3f2cc3d5fbfb7282b1e6 to your computer and use it in GitHub Desktop.
DjangoJSONEncoder sublcass that is (sort of) able to serialize Django objects.
class JSONEncoder(DjangoJSONEncoder):
""" Expands DjangoJsonEncoder to handle Django objects """
def _obj_to_dict(self, o):
""" Convert a Django object to plain dict
!!! HACK ALERT !!!
"""
# Get objects's dict. This gives us most fields, but some fields
# that reference other objects must be processed further later on.
data = o.__dict__
# Delete the Modelstate
del data['_state']
keys = data.keys()
# Look for any keys that end with _cache and also have a counterpart
# that end with _id, without the leading underscore.
for key in keys:
if key.endswith('_cache'):
base_key = key.replace('_cache', '')[1:]
# Do we have a match?
if '%s_id' % base_key in data:
# Serialize the related object as well
data[base_key] = self._obj_to_dict(data[key])
# Remove original keys
del data[key]
del data['%s_id' % base_key]
# Return resulting dict for serialization
return data
def default(self, o):
if isinstance(o, Model):
return self._obj_to_dict(o)
elif isinstance(o, QuerySet):
return [self._obj_to_dict(obj) for obj in o]
else:
return super(JSONEncoder, self).default(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment