Solution
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from flask_marshmallow import Marshmallow
app = Flask(__name__)
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Author(db.Model):
__tablename__ = "authors"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
books = db.relationship("Book",
backref=db.backref("author", lazy="joined"),
foreign_keys="Book.author_id",
lazy="dynamic"
)
class Book(db.Model):
__tablename__ = "books"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
author_id = db.Column(db.Integer, db.ForeignKey("authors.id"))
class BookSchema(SQLAlchemyAutoSchema):
class Meta:
model = Book
include_fk = True
load_instance = True
sqla_session = db.session
class AuthorSchema(SQLAlchemyAutoSchema):
class Meta:
model = Author
load_instance = True
# include_relationships = True # See below
sqla_session = db.session
books = ma.Nested(BookSchema, many=True)
with app.app_context():
db.drop_all()
db.create_all()
author = Author(name="Chuck Paluhniuk")
book = Book(title="Fight Club", author=author)
db.session.add(author)
db.session.add(book)
db.session.commit()
author_schema = AuthorSchema()
book_schema = BookSchema()
dump_data_author = author_schema.dump(author)
print(dump_data_author)
dump_data_book = book_schema.dump(book)
print(dump_data_book)
json = [
{'author_id': 1, 'title': 'Fight Club', 'id': 1}
]
schema = BookSchema(many=True)
print(schema.load(json))
json = [
{'books': [{'author_id': 1, 'title': 'Fight Club', 'id': 1}], 'name': 'Chuck Paluhniuk', 'id': 1}
]
schema = AuthorSchema(many=True)
print(schema.load(json))