我在 StructuredProperty
中有一个 ComputedProperty
,它在首次创建对象时不会更新。
当我创建对象时 address_components_ascii
没有被保存。该字段在数据存储查看器中根本不可见。但是,如果我 get()
然后立即再次 put()
(即使没有更改任何内容),ComputedProperty
也会按预期工作。 address_components
字段工作正常。
我已经尝试清除数据库,并删除整个数据库文件夹,但没有成功。
我在 Windows 7 上使用本地开发服务器。我没有在 GAE 上测试过它。
代码如下:
class Item(ndb.Model):
location = ndb.StructuredProperty(Location)
内部 Location 类:
class Location(ndb.Model):
address_components = ndb.StringProperty(repeated=True) # array of names of parent areas, from smallest to largest
address_components_ascii = ndb.ComputedProperty(lambda self: [normalize(part) for part in self.address_components], repeated=True)
归一化函数
def normalize(s):
return unicodedata.normalize('NFKD', s.decode("utf-8").lower()).encode('ASCII', 'ignore')
address_components
字段的示例:
[u'114B', u'Drottninggatan', u'Norrmalm', u'Stockholm', u'Stockholm', u'Stockholms l\xe4n', u'Sverige']
和 address_components_ascii
字段,在第二个 put()
之后:
[u'114b', u'drottninggatan', u'norrmalm', u'stockholm', u'stockholm', u'stockholms lan', u'sverige']
最佳答案
真正的问题似乎是 GAE 在 StructuredProperty
上调用 _prepare_for_put()
相对于调用 _pre_put_hook()
的顺序周围的 Model
。
我正在 Item._pre_put_hook()
中写入 address_components
。我假设 GAE 在调用 Item
上的 _pre_put_hook()
之前计算了 StructuredProperty
的 ComputedProperty
。从 ComputedProperty 读取会导致重新计算其值。
我将其添加到 _pre_put_hook()
的末尾:
# quick-fix: ComputedProperty not getting generated properly
# read from all ComputedProperties, to compute them again before put
_ = self.address_components_ascii
我将返回值保存到虚拟变量以避免 IDE 警告。
关于python - ComputedProperty 仅在第二次 put() 时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266237/