【问题标题】:Nesting Flask-SQLAlchemy relationship with Marshmallow使用 Marshmallow 嵌套 Flask-SQLAlchemy 关系
【发布时间】: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


    【解决方案1】:

    您可以通过PostSchema 中的Nested 字段轻松实现这一点(假设您使用的是marshmallow-sqlalchemy):

    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
    

    我建议您阅读Marshmallow's documentation about Nesting schemas 以了解不同的选项和参数。 此外,Marshmallow SQLAlchemy 的文档,尤其是“食谱”部分很有帮助,并提供了有关如何构建模式的想法。

    【讨论】:

    • 我收到了这个错误:ImportError: cannot import name 'Nested' from 'marshmallow_sqlalchemy.fields'
    • 取决于您使用的是flask-marshmallowmarshmallow-sqlalchemy 还是仅使用marshmallow。在您正在使用的模块的文档中检查您可以从何处获得此 Nested 字段对象。
    • 我使用的是flask-marshmallow,但它没有提到文档中的嵌套字段对象。所以我只是切换到 marshmallow_sqlalchemy。这是我的导入from flask import Flask, render_template from flask_socketio import SocketIO from flask_sqlalchemy import SQLAlchemy #from flask_marshmallow import Marshmallow from marshmallow import fields from marshmallow_sqlalchemy import ModelSchema from marshmallow_sqlalchemy.fields import Nested
    • 好了,您可以看到Nestedfields 模块的一部分。所以你可以使用fields.Nested() 而无需导入任何东西。您应该检查模块和包在 python 中是如何组织和导入的:realpython.com/python-modules-packages
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2020-04-14
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多