继带有祖先的键 http://endpoints-proto-datastore.appspot.com/examples/keys_with_ancestors.html示例,假设我们有相同的导入并定义了类MyParent
以同样的方式在那里定义。
TL;DR 的答案本质上是通过parent=
模型构造函数相当于创建一个键None
作为种类 ID 对列表中的最后一个 ID。例如,对于一个类MyModel
:
>>> parent = ndb.Key(MyModel, 1)
>>> child = MyModel(parent=parent)
>>> print child.key
ndb.Key('MyModel', 1, 'MyModel', None)
为了对示例执行此操作,我们可以简单地忽略id
:
class MyModel(EndpointsModel):
_parent = None
attr1 = ndb.StringProperty()
attr2 = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
并且在设置器中只需设置半生的密钥,不要尝试从数据存储中检索(因为密钥不完整):
def ParentSet(self, value):
if not isinstance(value, basestring):
raise TypeError('Parent name must be a string.')
self._parent = value
if ndb.Key(MyParent, value).get() is None:
raise endpoints.NotFoundException('Parent %s does not exist.' % value)
self.key = ndb.Key(MyParent, self._parent, MyModel, None)
self._endpoints_query_info.ancestor = ndb.Key(MyParent, value)
类似地,在 getter 中,您可以直接从键检索父级(尽管这并不能保证只有一对作为父级):
@EndpointsAliasProperty(setter=ParentSet, required=True)
def parent(self):
if self._parent is None and self.key is not None:
self._parent = self.key.parent().string_id()
return self._parent
完成此操作后,您无需更改任何 API 代码,该示例将按预期工作。