Adding a StructuredProperty to a Model in NDB

2019-07-29 09:21发布

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

3条回答
贪生不怕死
2楼-- · 2019-07-29 09:42

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

tutorialInstance.chapters.append(chap)
查看更多
唯我独甜
3楼-- · 2019-07-29 09:52

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.

查看更多
Deceive 欺骗
4楼-- · 2019-07-29 09:53

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.

查看更多
登录 后发表回答