目標:從實例的實例,其中模型是用不同的數據庫名稱定義獲取屬性的「Python的名字」獲取NDB模型實例的屬性,其中Python的名稱=數據存儲名稱
提供一些上下文中,我有一個自定義的to_dict()
序列化NDB模型的方法。該方法的核心是如下:
for key, prop in self._properties.iteritems():
if hasattr(self, key):
value = getattr(self,key)
# do typical to_dict() stuff
如果模型定義如下,一切都很好:
import Thing
class Example(ndb.Model):
things = ndb.KeyProperty(Thing, repeated=True)
不過,也有問題,如果它定義成Python的名字是things
但數據存儲名稱爲'Thing'
:
# no import req'd
class Example(ndb.Model):
things = ndb.KeyProperty('Thing', repeated=True)
在第一種情況下,從self._properties.iteritems()
的key
將things
。如果我有一個例子的例子,說example
,那麼hasattr(example,'things')
將評估爲真。
在第二種情況下,key
將Thing
和hasattr(example,'Thing')
將評估爲假,因爲實例的實例具有由Python名「東西」定義的屬性。
如何獲取實例的屬性? TIA。