I am using Django 1.11 and Python 2.7 with Google Appengine's NDB Library. I want to serialize my NDB model. I am following this.
models.py
class DictModel(ndb.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
class Post(DictModel):
text = ndb.StringProperty()
date = ndb.DateProperty(auto_now_add=True)
url = ndb.StringProperty()
url_title = ndb.StringProperty()
url_text = ndb.StringProperty()
privacy = ndb.StringProperty()
tags = ndb.StringProperty()
@classmethod
def query_post(cls, ancestor_key):
return cls.query(ancestor=ancestor_key).order(-cls.date)
views.py
@login_required()
def get_user_profile(request, username):
user = User.objects.get(username=username)
ancestor_key = ndb.Key(Post, username)
posts = Post.query_post(ancestor_key)
print(posts)
return HttpResponse(json.dumps([p.to_dict() for p in posts]), content_type='application/json')