【问题标题】:GAE Python: How to use NDB KeyProperty models for many-to-one relationship?GAE Python:如何使用 NDB KeyProperty 模型进行多对一关系?
【发布时间】: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,感谢您的意见。没有引号的部门似乎对我有用。它能够获取实体。

标签: python google-app-engine


【解决方案1】:

根据文档 (https://cloud.google.com/appengine/docs/python/datastore/entities),“Datastore API 不区分创建新实体和更新现有实体”。也就是说,put() 方法要么创建一个不存在的实体,要么更新一个现有的实体。

所以,选项 2 似乎是可行的方法。 (选项 1 确实不提供任何验证)

【讨论】:

  • 谢谢。正在考虑这是否相当于关系数据库中的引用约束。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多