我在GAE的数据存储区中有以下模型:
class Blog(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
我使用以下类创建了一个新帖子:
class NewPostHandler(Handler):
def render_newpost(self, subject="", content="", error=""):
self.render("newpost.html", subject=subject, content=content, error=error)
def get(self):
self.render_newpost()
def post(self):
subject = self.request.get("subject")
content = self.request.get("content")
if subject and content:
a = Blog(parent = blog_key(), subject=subject, content=content)
a.put()
self.redirect("/blog/%s" %str(a.key().id()))
else:
error = "we need both a subject and some text!"
self.render_newpost(subject, content, error)
我使用这段代码来定义一个键:
def blog_key(name = 'default'):
return db.Key.from_path('blogs', name)
我的问题是在尝试渲染时,以下使用get_by_id工作:
class PermalinkHandler(Handler):
def get(self, blog_id):
blog = Blog.get_by_id(int(blog_id), parent=None)
if not blog:
self.response.write('There is no blog whose id is %s' %blog_id)
return
self.render("permalink.html", blog = blog)
当我尝试用
替换blog = Blog.get_by_id(int(blog_id), parent=None)
时
k = db.Key.from_path('Blog', int(blog_id), parent=blog_key())
blog = db.get(k)
它不起作用,任何想法为什么? THX
答案 0 :(得分:1)
显而易见的问题是你在工作代码中提供父母。
def get(self, blog_id):
blog = Blog.get_by_id(int(blog_id), parent=None)
查看您的代码,父级始终为None,并且在您的帖子处理程序中,您没有向我们展示您如何创建blog_key
然后在您的非工作代码中
k = db.Key.from_path('Blog', int(blog_id), parent=blog_key())
blog = db.get(k)
所以我的猜测是问题是由于你的密钥中使用父项不一致。