python – 使用endpoint-proto-datastore时设置父键但不设置子键
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用endpoint-proto-datastore时设置父键但不设置子键,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1863字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用endpoint-proto-datastore时设置父键但不设置子键](/upload/InfoBanner/zyjiaocheng/723/b82783530ef84bfd8464dadcfe717545.jpg)
如何为EndpointsModel设置父/祖先,并让数据存储自动生成实体ID / Key?
我试图调整keys_with_ancestors样本,但似乎有点块,因为它需要指定id和parent.我想做类似的事情,除了只提供父ID或密钥,并由app引擎数据存储自动生成实体ID /密钥.
以下显示了如何使用NDB进行此操作.
class Parent(ndb.Model):
name = ndb.StringProperty()
class MyModel(ndb.Model):
attr1 = ndb.StringProperty()
attr2 = ndb.StringProperty()
p = Parent(name="Jerry")
p_key = p.put() # or retrieve the key from somewhere else
mod = MyModel(parent=p_key)
mod.put()
这是可能的吗?有人能指出我正确的方向吗?谢谢.
解决方法:
在keys_with_ancestors样本之后,让我们假设我们有相同的导入,并且以与在那里定义相同的方式定义了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)
并且在setter中只需设置半生不熟的密钥,不要尝试从数据存储区中检索(因为密钥不完整):
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代码,该示例将按预期工作.
内容总结
以上是互联网集市为您收集整理的python – 使用endpoint-proto-datastore时设置父键但不设置子键全部内容,希望文章能够帮你解决python – 使用endpoint-proto-datastore时设置父键但不设置子键所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。