Return to Snippet

Revision: 10289
at December 16, 2008 08:40 by tamuratetsuya


Initial Code
from google.appengine.ext import db
from google.appengine.api import datastore_types
from django.utils import simplejson
class JSONProperty(db.Property):
    def get_value_for_datastore(self, model_instance):
        value = super(JSONProperty, self).get_value_for_datastore(model_instance)
        return self._deflate(value)
    def validate(self, value):
        return self._inflate(value)
    def make_value_from_datastore(self, value):
        return self._inflate(value)
    def _inflate(self, value):
        if value is None:
            return {}
        if isinstance(value, unicode) or isinstance(value, str):
            return simplejson.loads(value)
        return value
    def _deflate(self, value):
        return simplejson.dumps(value)
    data_type = datastore_types.Text


class Person(db.Model):
    address_book = JSONProperty()
person = Person(address_book = {
    "alice": { "phone": "555-555-5555", "email": "[email protected]" } })
person.address_book["bob"] = { "email": "[email protected]" }
person.put()
...
some_person = db.get(key)
logging.info("Phone number for alice is " + some_person.address_book["alice"]["phone"])

Initial URL

                                

Initial Description

                                

Initial Title
Add a JSONProperty to your Model to save a dict to the datastore

Initial Tags
google, python, django

Initial Language
Python