Login

JsonObjectField

Author:
wattsmartin
Posted:
December 16, 2010
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 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.