Google ndb 中同一种类的不同实体可以同时有不同的 parents 吗?如果是,这有什么用?

Can different entities of the same kind have different parents in Google ndb at the same time? If yes, how is this useful?

在声明模型class时,没有限制添加parent键:

class Employee():
    name = ndb.StringProperty(required=True)

class Address():
    city = ndb.StringProperty(required=True)

class Education():
    college = ndb.StringProperty(required=True)

我们添加祖先路径的当前方式是在写入数据存储期间,如下所示

employee = Employee()
employee.put()

address1 = Address(parent=employee)

所以,没有什么能阻止一个人做:

address1 = Address(parent=employee)
address2 = Address(parent=education)

感觉有点奇怪!

是的,他们可以 - 父级实际上可以是任何类型的实体(或 None - 独立实体,也称为实体组所有者)。

你的例子就是这样一种用法。

至于可用性,它实际上取决于应用程序。如果您觉得它有用,那就是 :) 如果没有 - 您可能不会使用它。

例如,您的应用可能还包含企业实体或 colleges/universities,它们都至少有一个 Address 子实体与其相关联。

旁注:

  • 你应该让你的 classes 继承 ndb.Model class 来创建他们的实例 ndb 实体:

    class Address(ndb.Model):
    
  • 您应该在子创建中传递父实体的 key,而不是父实体本身:

    address1 = Address(parent=employee.key)