this is my proposition to have custom data inside a model field

a json data field, the code is simple as this, and it works with
lastest django release

from django.db import models
from django.core.serializers.json import simplejson, DjangoJSONEncoder
import StringIO

class JsonField(models.Field):
    __metaclass__ = models.SubfieldBase

    serialize_to_string = True

    def get_internal_type(self):
        return "TextField"

    def value_to_string(self, obj):
        return self.get_prep_value(self._get_val_from_obj(obj))

    def get_prep_value(self, value):
        if value:
            stream = StringIO.StringIO()
            simplejson.dump(value, stream, cls=DjangoJSONEncoder)
            value = stream.getvalue()
            stream.close()
            return value
        return None

    def to_python(self, value):
        if isinstance(value, (str, unicode)):
            value = StringIO.StringIO(value)
            return simplejson.load(value)
        return value

you can set a standard json object as data for a field, and the field
encode this as a json object when you save the model

example

obj.shopping_list = {"fruit":["apple", "banana"]}

it is also possibile to pass an ugettext_lazy object inside the
encoder, if we put a method to encode/decode lazy objects inside
DjangoJSONEncoder

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-developers@googlegroups.com.
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to