Login

JsonObjectField

Author:
wattsmartin
Posted:
December 16, 2010
Language:
Python
Version:
1.2
Tags:
model json database object
Score:
1 (after 1 ratings)

This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.

 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. Amazon S3 Enabled FileField and ImageField (with Boto) by natebeacham 4 years, 11 months ago
  2. An alternative model serializer for django models by isaact 6 years, 4 months ago
  3. JSON View Decorator by bryanpieper 4 years, 8 months ago
  4. SerializedObjectField by dominno 5 years ago
  5. Serialize JSON object into a model object and retrieve a python dictionary on load by cstrap 4 years, 4 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

#

Please login first before commenting.