NDB 中的一对多示例 [英] One-To-Many Example in NDB

查看:22
本文介绍了NDB 中的一对多示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建像学生和科目这样的 ndb.Model 类

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)

一个学生可以有多个科目.如何在此模型中添加和存储这些.我找不到任何例子.对于 String 属性 .. 有字段属性,即 repeat=true

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.

推荐答案

当我需要一对多时,我会使用重复的 keyProperties.代码:

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)

模板:

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

ndb 是 nosql,因此您不会在子级中找到对父级的引用.但是,您可以像这样添加它.创建新科目时不要忘记设置学生键值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆