我的NDB数据模型看起来像这样
class Foo(ndb.Model):
created = ndb.DateTimeProperty(auto_now_add=True)
# some other properties
@property
def readable_created(self):
return readble_time(self.created)
其中readable_time
返回日期时间的一些可读版本(例如"2 天前"(。多亏了@property装饰器,我可以轻松地将其作为myinstance.readable_created
访问。我想使用NDB的Model.to_dict()
方法将数据转换为字典,例如将其写入模板。但是,此方法会忽略readable_created
,myinstance.to_dict(include=['readable_created'])
返回{}
。
这是我第一次使用@property
装饰器,所以也许我错过了什么?有没有简单的解决方法?这是一个错误吗?
ndb to_dict方法的方法不包括对象的关键工作,但应该有一种更简单的方法。
谢谢!
这是设计使然。一些模板引擎允许您直接访问属性,因此您根本不需要使用 to_dict(((正如 Tim Hoffman 指出的那样(。