我遵循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)
当我查询作者表时,我想查看书籍表中的完整数据。
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))