Posted By

tamuratetsuya on 12/16/08


Tagged

google python engine app django


Versions (?)

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


 / Published in: Python
 

  1. from google.appengine.ext import db
  2. from google.appengine.api import datastore_types
  3. from django.utils import simplejson
  4. class JSONProperty(db.Property):
  5. def get_value_for_datastore(self, model_instance):
  6. value = super(JSONProperty, self).get_value_for_datastore(model_instance)
  7. return self._deflate(value)
  8. def validate(self, value):
  9. return self._inflate(value)
  10. def make_value_from_datastore(self, value):
  11. return self._inflate(value)
  12. def _inflate(self, value):
  13. if value is None:
  14. return {}
  15. if isinstance(value, unicode) or isinstance(value, str):
  16. return simplejson.loads(value)
  17. return value
  18. def _deflate(self, value):
  19. return simplejson.dumps(value)
  20. data_type = datastore_types.Text
  21.  
  22.  
  23. class Person(db.Model):
  24. address_book = JSONProperty()
  25. person = Person(address_book = {
  26. "alice": { "phone": "555-555-5555", "email": "[email protected]" } })
  27. person.address_book["bob"] = { "email": "[email protected]" }
  28. person.put()
  29. ...
  30. some_person = db.get(key)
  31. logging.info("Phone number for alice is " + some_person.address_book["alice"]["phone"])

Report this snippet  

You need to login to post a comment.