Flask-marshmallow 关系正常工作,从子表返回空对象

问题描述 投票:0回答:1

我遵循flask-marshmallow文档并编写了下面的代码,当我查询作者表时,我从书籍表中得到空书籍对象。你能告诉我我面临的问题是什么吗?

另外,我看到 pycharm 没有检测到 ma.Nested(),请问如何导入它?

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    # books = db.relationship("Book", backref="authors")
    # book_id = db.Column(db.Integer, db.ForeignKey("book.id"))


class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    author_id = db.Column(db.Integer, db.ForeignKey("author.id"))
    author = db.relationship("Author", backref="books")

class BookSchema(ma.SQLAlchemySchema):
    class Meta:
        model = Book
        include_fk = True

class AuthorSchema(ma.SQLAlchemySchema):
    class Meta:
        model = Author

    id = ma.auto_field()
    name = ma.auto_field()
    books = ma.Nested("BookSchema", many=True)


# Creation of the database tables within the application context.
with app.app_context():
    db.create_all()

author_schema = AuthorSchema(many=True)
book_schema = BookSchema(many=True)


@app.route('/', methods=["GET"])
def get_hello_world():
    queryDB = Author.query.all()
    result = author_schema.dump(queryDB)
    print(result)
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)

当我查询作者表时,我想查看书籍表中的完整数据。

flask flask-sqlalchemy marshmallow flask-marshmallow
1个回答
0
投票

books
中的
AuthorSchema
属性是嵌套对象的集合。因此,有必要将
List
Nested
和相应的模式结合使用。
为了不必单独定义所有属性,我还建议使用
SQLAlchemyAutoSchema

class BookSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Book
        include_fk = True

class AuthorSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Author
    books = ma.List(ma.Nested(BookSchema))
© www.soinside.com 2019 - 2024. All rights reserved.