【发布时间】:2019-09-07 04:23:59
【问题描述】:
我正在使用 flask_marshmallow (0.10.1) 将我的 flask_sqlalchemy 表中的数据序列化为 JSON 对象。
但是,这 2 个表(帖子和评论)之间存在关系。我做了一些研究,但我不确定如何使用嵌套或调用什么来正确序列化为 JSON。
这是我的 flask_sqlalchemy 类:
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
comments = db.relationship('Comment',backref='post_owner') #This needs an integer to increment im
def __repr__(self):
return f"Post({self.id}, {self.content}), {self.comments}"
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
comment = db.Column(db.Text, nullable=True)
owner_id = db.Column(db.Integer, db.ForeignKey('post.id'))
def __repr__(self):
return f"Comment {self.comment}"
然后这是我的 flask_marshmallow 模式:
class PostSchema(ma.ModelSchema):
class Meta:
model = Post
class CommentSchema(ma.ModelSchema):
class Meta:
model = Comment
最后是我调用模式序列化的函数:
def convert_to_json(post_to_convert):
post_schema = PostSchema()
output = post_schema.dump(post_to_convert)
return output
我得到的当前输出是这样的:
{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) [1, 2, 3]
我想要得到的(在 cmets 中:)是这样的:
{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) ["first comment", "second comment", "third comment"]
我需要实际的评论文本数据,而不仅仅是我得到的 ID 号。感谢任何帮助。
【问题讨论】:
标签: python flask-sqlalchemy marshmallow