我的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
返回DateTime的某些可读版本(例如'2天前')。感谢@property装饰器,我可以轻松地以myinstance.readable_created
的形式访问它。我想使用NDB的Model.to_dict()
方法将数据转换为字典,比如将其写入模板。但是,此方法会忽略readable_created
,myinstance.to_dict(include=['readable_created'])
会返回{}
。
这是我第一次使用@property
装饰器,所以也许我错过了什么?
有一个简单的方法吗?这是一个错误吗?
来自ndb to_dict method does not include object's key的方法有效,但应该有一种更简单的方法。
谢谢!
答案 0 :(得分:4)
这是设计的。一些模板引擎允许您直接访问属性,因此您根本不需要使用to_dict()(正如Tim Hoffman指出的那样)。