我们有一个ndb模型,希望使json可序列化。模型相当简单,大致如下:
class Pasta(ndb.Model):
name = ndb.StringProperty()
type = ndb.StringProperty()
comments = ndb.JsonProperty()
然后在处理程序方面,我们希望按照以下思路执行操作:
json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch())
并将其返回给客户机,但它不断抛出json解析错误,因为类Pasta不是json可序列化的。所以,问题是,我们必须实现__str__
或__repr__
还是有一种更好的方法来实现它?
或者您可以向模型添加计算属性,如下所示:
然后在get方法中,只要调用dict,就可以得到id
ndb.Model
实例有一个to_dict()
函数: https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict最简单的方法是:
我不相信有文档记录,但是对于现有的
ext.db
模型,可以使用db.to_dict()
(请参见here)。尽管使用
db.ReferenceProperty
和db.DateTimeProperty
时要小心,因为它们在调用json.dumps()
时会抛出错误。快速解决方案是自定义JSONEncoder:然后用这个编码:
相关问题 更多 >
编程相关推荐