我如何 add/change 实体的父级在创建之后但在放入数据存储区之前?

How can I add/change the parent of an entity after it has been created but before it is put in the Datastore?

根据我在文档中读到的内容,将实体放入数据存储区后,不可能更改实体的父级。但是我正在寻找一种方法来在此之前(但在创建之后)更改父级。所以不要这样:

John = Student(parent=BlueClassroom.key, name="John", last_name="Smith")
John.put()

我正在寻找这样的东西:

John = Student(name="John", last_name="Smith")
John.parent = BlueClassroom.key
John.put()

现在,第一个有效,但第二个无效(它只是忽略了第二行)。我也尝试过使用 populate,但这只适用于常规属性。有什么办法可以做到这一点吗?

根据 NDB Model Class Constructor 文档:

You cannot easily define a property named "key", "id", "parent", or "namespace". If you pass, for example, key="foo" in a constructor or populate() call, it sets the entity's key, not a property attribute named "key".

我建议在您准备好创建实体之前将数据作为字典传递:

john = {name="John", last_name="Smith"}
...
John = Student(parent=BlueClassroom.key)
John.populate(john)