【发布时间】:2015-10-15 11:39:59
【问题描述】:
我想创建一个实体对象,在它构建之后,在将它写入数据存储之前,我想设置父对象和 id。
根据App Engine docs,构造函数接受这些关键字参数:
- id
- key
- parent
您无法轻松定义名为“key”、“id”、“parent”或 “命名空间”。例如,如果您在构造函数中传递 key="foo" 或 populate() 调用,它设置实体的键,而不是属性属性 命名为“钥匙”。
对于populate(),它表示它将接受与构造函数相同的关键字参数。但是,我似乎做错了什么,因为唯一有效的关键字参数是key。使用 id 和/或 parent 会出错。
class Foo(ndb.Model):
pass
foo = Foo()
foo.populate(key=ndb.Key('Bar', 1, 'Foo', 123))
foo.key == ndb.Key('Bar', 1, 'Foo', 123) # True
当我改为使用关键字parent...
f.populate(parent=ndb.Key('Bar', 1))
...我得到了这个回溯:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2970, in _set_attributes
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
AttributeError: type object 'Foo' has no attribute 'parent'
或者有时这个(不确定是什么造成的不同):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2972, in _set_attributes
raise TypeError('Cannot set non-property %s' % name)
TypeError: Cannot set non-property parent
如果我使用id...
f.populate(id=123)
我又得到一个属性错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2960, in _populate
self._set_attributes(kwds)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2970, in _set_attributes
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
AttributeError: type object 'Foo' has no attribute 'id'
我上面的所有populate() 示例不都应该与任何关键字参数一起使用吗?
我知道,我只能使用 key 来达到与 parent 和 id 一起使用的效果,但我想知道我在这里缺少什么。
【问题讨论】:
标签: python google-app-engine app-engine-ndb google-cloud-datastore