![](/img/trans.png)
[英]One-to-many relationship children throw "One or more instances could not be made persistent"
[英]One-To-Many Example in NDB
我正在嘗試像學生和科目一樣創建 ndb.Model class
class Subject(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
subject = ndb.KeyProperty(kind=Subject)
一個學生可以有很多科目。 如何在這個 Model 中添加和存儲這些。我找不到任何示例。 對於 String Property.. 有字段屬性,即 repeat=true
如何實現這一點,web 上是否有任何工作示例。抱歉,如果這是重復的問題,但我嘗試用我有限的技能搜索這個論壇。
當我需要一對多時,我會使用重復的 keyProperties。 代碼:
class Subject(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
subjects = ndb.KeyProperty(kind='Subject', repeated=True)
模板:
{% for subject in student.subjects %}
{{subject.get().name}}
{% endfor %}
ndb 是 nosql 所以你不會在孩子中找到對父母的引用。 但是,您可以這樣添加它。 創建新科目時不要忘記設置學生鍵值。
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)
使用主題作為關鍵字。
me = Student(key_name='KurzedMetal')
programming = Subject(key_name='Programming')
programming.put()
me.subject = programming.key()
me.put()
定義:
class Subject(ndb.Model):
name = ndb.StringProperty()
class Student(ndb.Model):
name = ndb.StringProperty()
subject = ndb.KeyProperty(kind=Subject,repeated=True)
用法:
subject1 = Subject()
subject1.put()
subject2 = Subject()
subject2.put()
student = Student()
student.subject.append(subject1.key)
student.subject.append(subject2.key)
student.put()
這看起來像一個老問題。 如果其他人目前需要這個,您應該查看Structured Properties
https://developers.google.com/appengine/docs/python/ndb/properties#structured 。 該示例非常清晰且易於理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.