try: import json except ImportError: from django.utils import simplejson as json from django.db import models class JsonDescriptor(property): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: return self if self.field.name not in instance.__dict__: raw_data = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = self.field.unpack(raw_data) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, self.field.pack(value)) class JsonObjectField(models.TextField): """This is a specialized incarnation of the Django TextField, designed to transparently pack/unpack objects into JSON representations. """ def pack(self, obj): return json.dumps(obj) def unpack(self, data): return json.loads(str(data)) def get_attname(self): return '%s_json' % self.name def contribute_to_class(self, cls, name): super(JsonObjectField, self).contribute_to_class(cls, name) setattr(cls, name, JsonDescriptor(self))