Adding a StructuredProperty to a Model in NDB

℡╲_俬逩灬. 提交于 2019-12-11 08:44:02

问题


(couldn't think of a better title :S )

So I've recently changed from db to ndb and i can't get one part to work. I have this tutorial model that has chapters, so I am using 'ndb.StructuredProperty' to associate the model Chapter to the tutorial. I can create the tutorials and the chapter with no problems but i can't point the chapters to the tutorial.

The Tutorial Model:

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)

The Edit Class:

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')

Using this code the tutorial is created but i get this error:

tutorialInstance.chapters = chap
AttributeError: 'NoneType' object has no attribute 'chapters'

回答1:


You seem to be confused. When using StructuredProperty, the contained object doesn't have its own ID or key -- it's just more properties with funny names in the outer object. Perhaps you want a repeated KeyProperty linking the book to its chapters rather than having all the chapters contained inside the book? You have to choose one or the other.




回答2:


You are dealing with a list... you need to append the object to the list

tutorialInstance.chapters.append(chap)



回答3:


Update: with the help of @nizz, changing

tutorialInstance = tutorial.get()
tutorialInstance.chapters = chap

to:

tutorialInstance = ndb.Key('Tutorial', int(tutID)).get()
tutorialInstance.chapters.append(chap)

worked perfectly.



来源:https://stackoverflow.com/questions/14611923/adding-a-structuredproperty-to-a-model-in-ndb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!