I\'ve been searching for quite a while with no success. My project isn\'t using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model)
As mentioned by https://stackoverflow.com/users/806432/fredva, the to_dict works great. Here is my code i'm using.
foos = query.fetch(10)
prepJson = []
for f in foos:
prepJson.append(db.to_dict(f))
myJson = json.dumps(prepJson))
This is the simplest solution I found. It requires only 3 lines of codes.
Simply add a method to your model to return a dictionary:
class DictModel(db.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
SimpleJSON now works properly:
class Photo(DictModel):
filename = db.StringProperty()
title = db.StringProperty()
description = db.StringProperty(multiline=True)
date_taken = db.DateTimeProperty()
date_uploaded = db.DateTimeProperty(auto_now_add=True)
album = db.ReferenceProperty(Album, collection_name='photo')
from django.utils import simplejson
from google.appengine.ext import webapp
class PhotoHandler(webapp.RequestHandler):
def get(self):
photos = Photo.all()
self.response.out.write(simplejson.dumps([p.to_dict() for p in photos]))