【问题标题】:Get properties of ndb model instance where Python name != datastore name获取 ndb 模型实例的属性,其中 Python 名称!= 数据存储名称
【发布时间】: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 将是 Thinghasattr(example,'Thing') 将评估为 False,因为 Example 的实例具有由 Python 名称“事物”定义的属性。

如何获取实例的属性? TIA。

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案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 方法)以允许进一步调整。

    因此,将您的两个示例都编码为 Example1 和 Example2,它们的 _properties.items() 分别是:

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

    他们的._to_dict(),根据需要,都相等

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

    【讨论】:

    • 这个答案的关键是.itervalues()。如果只是遍历self._properties,每个prop 都将是一个字符串,那么它就没有_code_name_verbose_name 之类的属性
    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多