One-To-Many Example in NDB

白昼怎懂夜的黑 提交于 2019-12-01 04:02:45

When I need 1 to many I use repeated keyProperties. Code:

class Subject(ndb.Model):
     name = ndb.StringProperty()

class Student(ndb.Model):
    name = ndb.StringProperty()
    subjects = ndb.KeyProperty(kind='Subject', repeated=True)

template:

{% for subject in student.subjects %}
  {{subject.get().name}}
{% endfor %}

ndb is nosql so you will not find reference to the parent in the child. However, you could add it like that. Don't forget to set student key value when creating a new subject.

class Subject(ndb.Model):
     name = ndb.StringProperty()
     student = ndb.KeyProperty(kind='Student')

class Student(ndb.Model):
    name = ndb.StringProperty()
    subjects = ndb.KeyProperty(kind='Subject', repeated=True)

Use the subject as a key.

me = Student(key_name='KurzedMetal')
programming = Subject(key_name='Programming')
programming.put()
me.subject = programming.key()
me.put()

Definition:

class Subject(ndb.Model):
     name = ndb.StringProperty()

class Student(ndb.Model):
    name = ndb.StringProperty()
    subject = ndb.KeyProperty(kind=Subject,repeated=True)

Usage:

subject1 = Subject()
subject1.put()
subject2 = Subject()
subject2.put()
student = Student()
student.subject.append(subject1.key)
student.subject.append(subject2.key)
student.put()

This looks like an old question. In case someone else needs this presently, you should look at Structured Properties https://developers.google.com/appengine/docs/python/ndb/properties#structured. The example is very clear and easy to follow.

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