[英]Jsonify flask-sqlalchemy many-to-one relationship in flask
I was trying to make rest apis with flask-restful where i am using flask-sqlalchemy as the ORM.Here is my model classes. 我试图用烧瓶休息来制作休息api,我使用flask-sqlalchemy作为ORM.Here是我的模型类。
class Post(db.Model):
__tablename__ = 'post'
postid = db.Column(db.Integer,primary_key=True)
post = db.Column(db.String(64))
userid = db.Column(db.Integer,db.ForeignKey('user.userid'))
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.author
}
and 和
class User(db.Model):
userid = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(30))
email = db.Column(db.String(20))
posts = db.relationship('Post',backref="author",lazy='dynamic')
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'username': self.username,
'email': self.email
}
And the database is populated.now i am trying to make the json out of this 并且数据库已填充。现在我正试图让json脱离这个
class PostList(Resource):
def get(self):
posts = DL_models.Post.query.all()
posts = [post.serialize for post in posts]
return { 'posts': posts }
api.add_resource(PostList, '/twitter/api/v1.0/posts', endpoint = 'posts')
This works perfect when i change serialize method in Post to 当我在Post中更改序列化方法时,这非常有效
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.postid
}
This returns expected json output but when i am changing to 'author':self.author
i am getting a error 这会返回预期的json输出,但是当我更改为
'author':self.author
我收到错误
TypeError: <app.DL_models.User object at 0x7f263f3adc10> is not JSON serializable
I understand that i have to call serialize on those nested objects as well but i could not figure out how to do it. 我知道我必须在这些嵌套对象上调用序列化,但我无法弄清楚如何做到这一点。
Or please share your experience to encode relationships in sqlalchemy. 或者请分享您的经验,以编码sqlalchemy中的关系。
Since you're already using Flask-Restful, have you considered using their built in data marshaling solution ? 由于您已经在使用Flask-Restful,您是否考虑过使用其内置的数据编组解决方案 ?
However, for marshaling complex data structures, I find that Marshmallow does the task about a thousand times better, even making nesting serializers within others easy. 然而,对于编组复杂的数据结构,我发现Marshmallow的任务要好一千倍,甚至可以轻松地将嵌套序列化器放在其他任务中。 There's also a Flask extension designed to inspect endpoints and output URLs.
还有一个Flask扩展,旨在检查端点和输出URL。
This is a punt but have you tried the below? 这是一个平底船但是你试过下面的吗?
'author': self.author.username
'author':self.author.username
From the error message I'm guessing it's getting to User but doesn't know what you want from it. 从错误消息我猜它到了用户,但不知道你想从中得到什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.