【发布时间】:2016-08-28 16:57:31
【问题描述】:
有关于如何set、get、KeyProperty/StructuredProperty 的帖子,但没有告诉我如何使用 NDB 进行多对一建模。
我有两个模型:
class Department(ndb.Model):
department_id = ndb.IntegerProperty()
name = ndb.StringProperty()
class Student(ndb.Model):
student_id = ndb.IntegerProperty()
name = ndb.StringProperty()
dept = ndb.KeyProperty(Kind=Department)
如何确保多对一,即每当插入学生记录时,它必须验证部门密钥 w.r.t 到部门数据存储?
如何插入学生记录以确保多对一关系?
选项 1:
# Insert student record without checking for valid dept id. GAE automatically validates
student = Student(student_id=...., dept=ndb.Key(Department, input_dept_id))
选项 2:
# check for valid dept id and then insert student record
dept_key = ndb.Key(Department, input_dept_id)
if(dept_key.get()):
student = Student(student_id=...., dept=dept_key)
我尝试了选项 1,其 dept_id 不在部门实体中,并且它能够插入该学生实体。我对 GAE 还很陌生。
【问题讨论】:
-
GAE 不会“验证”您的密钥,并允许您使用您想要的任何密钥,即使它不指向现有实体。您需要确保自己使用有效的密钥。您的选项 2 是一种解决方案。
-
需要注意的一点是,您的代码将 Department 作为一个类。所以每个 Key 构造函数中的 Department 应该是“Department” -
Student(student_id=...., dept=ndb.Key("Department", input_dept_id)) -
@TimHoffman,感谢您的意见。没有引号的部门似乎对我有用。它能够获取实体。