我正在使用 Google Appengine 和 Python 学习 Udacity 的 Web 开发类(class)。
我想知道如何分配给一个创建的实体,即它自己的作者。
例如,我有两种 ndb.Models 类型:
class User(ndb.Model):
username = ndb.StringProperty(required = True)
bio = ndb.TextProperty(required = True)
password = ndb.StringProperty(required = True)
email = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
class Blog(ndb.Model):
title = ndb.StringProperty(required = True)
body = ndb.TextProperty(required = True)
created = ndb.DateTimeProperty(auto_now_add = True)
当登录用户创建博客实体时,也应使用它来标识其自己的作者(用户实体)。
最终,我想显示博客文章及其作者信息(例如,作者的简介)
如何实现这一目标?
最佳答案
您的 Blog
类应包含一个属性来存储编写该博客的用户的 key :
author = ndb.KeyProperty(required = True)
然后,您可以在创建 Blog 实例时设置此属性:
blog = Blog(title="title", body="body", author=user.key)
为了优化,如果您知道登录用户的ndb.Key,并且不需要用户实体本身,则可以直接传递它,而不需要先获取用户。
assert isinstance(user_key, ndb.Key)
blog = Blog(title="title", body="body", author=user_key)
全文:
class User(ndb.Model):
username = ndb.StringProperty(required = True)
password = ndb.StringProperty(required = True)
email = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
class Blog(ndb.Model):
title = ndb.StringProperty(required = True)
body = ndb.TextProperty(required = True)
created = ndb.DateTimeProperty(auto_now_add = True)
author = ndb.KeyProperty(required = True)
def new_blog(author):
"""Creates a new blog post for the given author, which may be a ndb.Key or User instance"""
if isinstance(author, User):
author_key = author.key
elif isinstance(author, ndb.Key):
assert author.kind() == User._get_kind() # verifies the provided ndb.Key is the correct kind.
author_key = author
blog = Blog(title="title", body="body", author=author_key)
return blog
如果您将 new_blog 的开头标准化为实用函数,您可能会获得奖励积分。
关于python - 在创建实体期间将作者分配给实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20005657/