Skip to content

Instantly share code, notes, and snippets.

@erickdsama
Created January 31, 2018 19:41
Show Gist options
  • Select an option

  • Save erickdsama/92ec20838773533fc6563742b6971ce7 to your computer and use it in GitHub Desktop.

Select an option

Save erickdsama/92ec20838773533fc6563742b6971ce7 to your computer and use it in GitHub Desktop.
Model JSONField
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