目标:从Example的实例中获取属性的“ 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)
在第一种情况下,key
fromself._properties.iteritems()
将为things
。如果我有Example的实例,请说example
,则结果hasattr(example,'things')
将为True。
在第二种情况下,key
beth为Thing
且hasattr(example,'Thing')
将评估为False,因为Example实例的属性由Python名称“ things”定义。
如何获取实例的属性?TIA。
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
方法)委托给了属性本身以允许进一步调整。
结果,将您的两个示例都编码为Example1和Example2,它们_properties.items()
的整体分别是:
[('things', KeyProperty('things', repeated=True, kind='Thing'))]
[('Thing', KeyProperty('Thing', repeated=True))]
它们._to_dict()
,根据需要,两者相等
{'things': [Key('Thing', 'roro')]}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句