1

目標:從實例的實例,其中模型是用不同的數據庫名稱定義獲取屬性的「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()keythings。如果我有一個例子的例子,說example,那麼hasattr(example,'things')將評估爲真。

在第二種情況下,keyThinghasattr(example,'Thing')將評估爲假,因爲實例的實例具有由Python名「東西」定義的屬性。

如何獲取實例的屬性? TIA。

回答

1

ndb自己Model._to_dict方法做它,如下所示(簡化):

for prop in self._properties.itervalues(): 
    name = prop._code_name 
    values[name] = prop._get_for_dict(self) 

所以:名字是從每個屬性的_code_name(不是其主要採取self._properties,並且該值被委託給。屬性本身(通過其_get_for_dict方法),以允許進一步的調整

其結果是,編碼兩者的你的例子如例1和例2,其整體_properties.items()分別爲:

[('things', KeyProperty('things', repeated=True, kind='Thing'))] 
[('Thing', KeyProperty('Thing', repeated=True))] 

._to_dict(),如需要的話,都等於

{'things': [Key('Thing', 'roro')]}