Created
January 31, 2018 19:41
-
-
Save erickdsama/92ec20838773533fc6563742b6971ce7 to your computer and use it in GitHub Desktop.
Model JSONField
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
| import json | |
| from django import forms | |
| from django.db import models | |
| class JsonField(models.TextField): | |
| # object ready to python | |
| def to_python(self, value): | |
| if value is None: | |
| return value | |
| if isinstance(value, dict): | |
| return value | |
| return json.dumps(value) | |
| # Original class field | |
| def get_internal_type(self): | |
| return 'TextField' | |
| # prepare value to show in front | |
| def from_db_value(self, value, expression, connection): | |
| if value is None: | |
| return value | |
| return json.loads(value) | |
| # prepare value to DB | |
| def get_prep_value(self, value): | |
| if isinstance(value, dict): | |
| return json.dumps(value) | |
| return value | |
| def value_to_string(self, obj): | |
| return json.dumps(obj) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment