【发布时间】:2015-02-10 14:49:08
【问题描述】:
目标:从 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)
在第一种情况下,来自self._properties.iteritems() 的key 将是things。如果我有一个 Example 的实例,比如 example,那么 hasattr(example,'things') 的计算结果为 True。
在第二种情况下,key 将是 Thing,hasattr(example,'Thing') 将评估为 False,因为 Example 的实例具有由 Python 名称“事物”定义的属性。
如何获取实例的属性? TIA。
【问题讨论】:
标签: python google-app-engine google-cloud-datastore app-engine-ndb