Python 棉花糖筑巢与炼金术的关系

Python 棉花糖筑巢与炼金术的关系,python,flask-sqlalchemy,marshmallow,Python,Flask Sqlalchemy,Marshmallow,我使用flask_marshmallow(0.10.1)将flask_sqlalchemy表中的数据序列化为JSON对象 但是,这两个表(Post和Comments)之间存在关系。我做了一些研究,但我不确定如何使用嵌套或调用什么来正确序列化为JSON 以下是我的炼金术课程: class Post(db.Model): id=db.Column(db.Integer,主键=True) content=db.Column(db.Text,null=False) comments=db.relatio

我使用flask_marshmallow(0.10.1)将flask_sqlalchemy表中的数据序列化为JSON对象

但是,这两个表(Post和Comments)之间存在关系。我做了一些研究,但我不确定如何使用嵌套或调用什么来正确序列化为JSON

以下是我的炼金术课程:

class Post(db.Model):
id=db.Column(db.Integer,主键=True)
content=db.Column(db.Text,null=False)
comments=db.relationship('Comment',backref='post_owner')#这需要一个整数来增加im
定义报告(自我):
返回f“Post({self.id},{self.content}),{self.comments}”
类注释(db.Model):
id=db.Column(db.Integer,主键=True)
comment=db.Column(db.Text,nullable=True)
owner\u id=db.Column(db.Integer,db.ForeignKey('post.id'))
定义报告(自我):
返回f“Comment{self.Comment}”
下面是我的摇瓶棉花糖模式:

class PostSchema(ma.ModelSchema):
类元:
型号=员额
类CommentSchema(ma.ModelSchema):
类元:
模型=注释
最后是我调用模式进行序列化的函数:

def convert_to_json(post_to_convert):
post_schema=PostSchema()
输出=post\u schema.dump(post\u-to\u转换)
返回输出
我得到的电流输出如下:

{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) [1, 2, 3] 
我想(在评论:)得到的是:


我需要的是实际的评论文本数据,而不仅仅是我得到的Id号。非常感谢您的帮助。

您可以通过
PostSchema
中的
嵌套
字段轻松实现这一点(假设您使用的是
棉花糖sqlalchemy
):

我建议您阅读以了解不同的选项和参数。
另外,的文档,特别是“配方”部分很有帮助,并提供了如何构建模式的想法。

我遇到了以下错误:
ImportError:无法从“marshmallow\u sqlalchemy.fields”导入名称“Nested”
取决于您是否使用
flask marshmallow
marshmallow-sqlalchemy
或just
marshmallow
。在您正在使用的模块的文档中,检查您可以从何处获得此
嵌套的
字段对象。我使用的是flask marshmallow,但文档中没有提到嵌套的字段对象。所以我就换成了棉花糖炼金术。下面是我从flask导入flask的导入
,从flask导入flask的渲染模板\u socketio从flask导入socketio从flask\u sqlalchemy导入sqlalchemy#从flask\u marshmallow导入marshmallow导入字段从marshmallow\u sqlalchemy.fields导入嵌套的,您可以看到
Nested
fields
模块的一部分。因此,您可以使用
fields.Nested()
,而无需导入任何内容。您应该检查模块和包在python中是如何组织和导入的:
{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) ["first comment", "second comment", "third comment"] 
from marshmallow_sqlalchemy.fields import Nested

class PostSchema(ma.ModelSchema):
    class Meta:
        model = Post
    comments = Nested(CommentSchema, many=True)

class CommentSchema(ma.ModelSchema):
    class Meta:
        model = Comment