flaskflask-sqlalchemymarshmallowflask-marshmallow

Flask-marshmallow relationship is working properly returning empty object from child table


I followed flask-marshmallow documentation and written below code, when i query author table i get empty books object from books table. Can you tell me what is the issue I am facing ?

also, i see pycharm is not detecting ma.Nested(), any way how to import it ?

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)

I want to see full data from books table when i query author table.


Solution

  • The books attribute in the AuthorSchema is a collection of nested objects. For this reason it is necessary to use List in conjunction with Nested and the respective schema.
    In order not to have to define all attributes individually, I also recommend using 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))