JsonObjectField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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))

More like this

  1. Custom model field to store dict object in database by rudyryk 3 years, 1 month ago
  2. MarkdownTextField by carljm 4 years, 10 months ago
  3. Serialize JSON object into a model object and retrieve a python dictionary on load by cstrap 2 years, 6 months ago
  4. Pickled Object Field by obeattie 5 years, 5 months ago
  5. CodeLookupField by girasquid 3 years, 11 months ago

Comments

Hugotox (on July 17, 2012):

Great snippet! Thank you very much!

#

Hugotox (on July 17, 2012):

Actually at first glance seems to work but it does not save to database

#

(Forgotten your password?)