AppEngine 使 ndb 模型 json 可序列化 [英] AppEngine Making ndb models json serializable

查看:37
本文介绍了AppEngine 使 ndb 模型 json 可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 ndb 模型,我们想让 json 序列化.这些模型相当简单:

We have an ndb model that we would like to make json serializable. The models are fairly simple along the lines of:

class Pasta(ndb.Model):
   name = ndb.StringProperty()
   type = ndb.StringProperty()
   comments = ndb.JsonProperty()

然后在处理程序方面我们想做一些事情:

Then on the handler side we would like to do something along the lines of:

json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch()) 并将其返回给客户端,但它一直抛出 json 解析错误,因为类 Pasta不是 json 可序列化的.所以,问题是,我们是否必须实现 __str____repr__ 或者有更漂亮的方法来做到这一点?

json.dumps(Pasta.query(Pasta.name=="Ravioli").fetch()) and return it to the client, but it keeps throwing json parse errors since the class Pasta is not json serializable. So, the question is, do we have to implement __str__ or __repr__ or is there a niftier way to do it?

推荐答案

ndb.Model 实例有一个 to_dict() 函数:https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict

ndb.Model instances have a to_dict() function: https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict

最简单的方法是:

json.dumps([p.to_dict() for p in Pasta.query(Pasta.name == "Ravioli").fetch()])

这篇关于AppEngine 使 ndb 模型 json 可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆