Created
October 12, 2017 16:52
-
-
Save strikaco/b8e9b1a2cb954edacc665bd1ffa3d641 to your computer and use it in GitHub Desktop.
Django Model JsonHandler
This file contains hidden or 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
| 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