I am using a Django custom field to represent JSON encoded data:
class JSONField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value == "":
return None
try:
if isinstance(value, basestring):
return json_decode(value)
except ValueError:
pass
return value
def get_prep_value(self, value):
if value == "":
return None
if isinstance(value, dict) or isinstance(value, dict):
value = json_encode(value)
return super(JSONField, self).get_prep_value(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value,connection=None)
The field itself works great. However, editing through the admin site is not possible, since the string from the database is JSON-decoded and converted to a dictionary, so when rendering the admin site, the actual JSON string from the database is displayed (for example, {"foo": "bar"}), but its vocabulary representation (for example, {u'foo ': u'bar'}).
Obviously, this leads to problems when saving the database object, since the representation of the dictionary string is not a valid JSON string.
, , - , (.. , ), Python, to_python.
, , json_encode - ?