【发布时间】:2019-03-30 00:12:03
【问题描述】:
我将 Django 1.11 和 Python 2.7 与 Google Appengine 的 NDB 库一起使用。我想序列化我的 NDB 模型。我关注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')
【问题讨论】:
-
您使用的答案不是针对 ndb,而是针对更旧的 db 库。 ndb 有一个内置的
to_dict方法你可以使用。 -
通过使用内置,我得到一个错误 datetime.date(2006, 11, 1) is not JSON serializable。如何解决?
标签: django python-2.7 app-engine-ndb jsonserializer