在NDB模型中添加StructuredProperty
(想不出更好的标题 :S )
最近我把数据库从 db 换成了 ndb,但有一个部分我就是搞不定。我有一个教程模型,它里面有章节,所以我用 'ndb.StructuredProperty' 来把章节模型和教程关联起来。创建教程和章节都没问题,但我就是无法把章节指向对应的教程。
教程模型:
class Tutorial(ndb.Model):
title = ndb.StringProperty(required=True)
presentation = ndb.TextProperty(required=True)
extra1 = ndb.TextProperty()
extra2 = ndb.TextProperty()
extra3 = ndb.TextProperty()
tags = ndb.StringProperty(repeated=True)
votes = ndb.IntegerProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
last_modified = ndb.DateTimeProperty(auto_now=True)
chapters = ndb.StructuredProperty(Chapter, repeated=True)
编辑类:
class EditTut(FuHandler):
def get(self):
...
...
def post(self):
editMode = self.request.get('edit')
if editMode == '2':
...
...
elif editMode == '1':
tutID = self.request.cookies.get('tut_id', '')
tutorial = ndb.Key('Tutorial', tutID)
title = self.request.get("chapTitle")
content = self.request.get("content")
note = self.request.get("note")
chap = Chapter(title=title, content=content, note=note)
chap.put()
tutorialInstance = tutorial.get()
tutorialInstance.chapters = chap
tutorialInstance.put()
self.redirect('/editTut?edit=%s' % '0')
else:
self.redirect('/editTut?edit=%s' % '1')
用这段代码可以创建教程,但我遇到了这个错误:
tutorialInstance.chapters = chap
AttributeError: 'NoneType' object has no attribute 'chapters'
3 个回答
1
你正在处理一个列表……你需要把这个对象添加到列表里。
tutorialInstance.chapters.append(chap)
2
你似乎有点困惑。当使用 StructuredProperty
时,里面的对象没有自己的ID或键,它只是外部对象里一些名字比较奇怪的属性。也许你想要一个重复的 KeyProperty
来 连接 书籍和它的章节,而不是把所有章节都 放在 书里面?你需要在这两种方式中选择一种。
1
更新:在@nizz的帮助下,
把
tutorialInstance = tutorial.get()
tutorialInstance.chapters = chap
改成:
tutorialInstance = ndb.Key('Tutorial', int(tutID)).get()
tutorialInstance.chapters.append(chap)
效果很好。