我想創建一個實體對象,並在其構建之後,在將其寫入數據存儲之前,我想要設置父對象和ID。爲什麼我使用NDB的`populate()`不接受`id`或`parent`,而只接受`key`?
據App Engine docs,構造函數接受以下關鍵字參數: - id
- key
- parent
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".
爲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
一樣的一樣,但是我想知道我在這裏錯過了什麼。