Skip to content

Instantly share code, notes, and snippets.

@strikaco
Created October 12, 2017 16:52
Show Gist options
  • Save strikaco/b8e9b1a2cb954edacc665bd1ffa3d641 to your computer and use it in GitHub Desktop.
Save strikaco/b8e9b1a2cb954edacc665bd1ffa3d641 to your computer and use it in GitHub Desktop.
Django Model JsonHandler
class JsonHandler(object):
"""
Handles serialization/deserialization of attributes in the JSON blob.
Requires a field of type TextField named 'blob' on the source model.
These are not searchable unless you do FTS on the obj.blob field!
"""
def __init__(self, node, *args, **kwargs):
# Must set via dict interface or else it triggers __setattr__
# which obviously doesn't work with these parameters
self.__dict__['obj'] = node
def __getattr__(self, attr, *args, **kwargs):
# Deserialize the JSON object
dic = json.loads(self.obj.blob)
# Return the attribute requested
return dic.get(attr, None)
def __setattr__(self, key, value, *args, **kwargs):
# Deserialize the JSON object
dic = json.loads(self.obj.blob)
# Store the data
dic[key] = value
# Serialize the dictionary
self.obj.blob = json.dumps(dic, indent=4)
def update(self, d, *args, **kwargs):
# Deserialize the JSON object
dic = json.loads(self.obj.blob)
# Store the data
dic.update(**d)
# Serialize the dictionary
self.obj.blob = json.dumps(dic, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment