NDB中的一对多示例 [英] One-To-Many Example in NDB
问题描述
我试图创建类似学生和科目的ndb.Model类
class Subject(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
subject = ndb.KeyProperty(kind = Subject)
一个学生可以有许多科目。如何在这个模型中添加和存储这些。我找不到任何例子。对于字符串属性..有字段属性,即repeat = true
如何实现这一点,并在网络上有任何工作示例。对不起,如果它是重复的问题,但我试图用我有限的技能来搜索这个论坛。
使用重复的keyProperties。
代码:
class主题(ndb.Model):
name = ndb.StringProperty()
学生(ndb.Model):
name = ndb.StringProperty()
科目= ndb.KeyProperty(kind ='Subject',重复= True)
$ b $ p $ {%for subject in student.subjects%}
{{subject.get()。name}}
{%endfor%}
ndb是nosql,因此您不会在子项中找到对父项的引用。
但是,您可以像这样添加它。创建新主题时不要忘记设置学生键值。
class主题(ndb.Model):
name = ndb.StringProperty()
student = ndb.KeyProperty(kind ='Student')
$ b $ class Student(ndb.Model):
name = ndb.StringProperty( )
subjects = ndb.KeyProperty(kind ='Subject',repeated = True)
I am trying to create ndb.Model class like Students and subjects
class Subject(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
subject = ndb.KeyProperty(kind=Subject)
One Student can have many Subjects. How to add and store these in this Model. I could not find any example of it. For String Property .. there is field property i.e. repeat=true
How to achieve this and is there any working example on the web. Sorry if it is duplicate question but I tried with my limited skills to search this forum.
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)
这篇关于NDB中的一对多示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!