Flask Marshmallow/SqlAlchemy: Serializing many-to-

2020-02-28 06:53发布

问题:

I'm building a small REST api using Flask, flask-sqlalchemy and flask-marshmallow. For some requests I'd like to return a json serialized response consisting of my sqlalchemy objects. However I cant get the serialization to work with eagerly loaded sqlalchemy objects when using many-to-many relationships / secondary tables.

Here is a simple example, more or less copy/pasted from flask-marshmallow docs:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from sqlalchemy.orm import joinedload

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'

# Order matters: Initialize SQLAlchemy before Marshmallow
db = SQLAlchemy(app)
ma = Marshmallow(app)

secondary_foo = db.Table('secondary_foo',
                            db.Column('author_id', db.Integer, db.ForeignKey('author.id')),
                            db.Column('book_id', db.Integer, db.ForeignKey('book.id')))

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    authors = db.relationship('Author', secondary="secondary_foo", backref='books', lazy="joined")

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

class BookSchema(ma.ModelSchema):
    #authors = ma.Nested(AuthorSchema) <-- Doesn't work, authors will be serialized to empty json object, instead of list of ids
    class Meta:
        model = Book


db.drop_all()
db.create_all()
author_schema = AuthorSchema()
book_schema = BookSchema()
author = Author(name='Chuck Paluhniuk')
book = Book(title='Fight Club')
book.authors.append(author)
db.session.add(author)
db.session.add(book)
db.session.commit()

s = BookSchema(many=True)

Based on the above code I can load books eagerly and get the authors objects as well. But when serializing the deep objects are serialized into a list of IDs:

print(Book.query.filter(1==1).options(joinedload('authors')).all()[0].authors)
//--> [<__main__.Author object at 0x1043a0dd8>]

print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data)
//--> [{'authors': [1], 'title': 'Fight Club', 'id': 1}]

This is the result I want:

print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data)
//--> [{'authors': [{'name':'Chuck Paluhniuk', 'id':'1'}], 'title': 'Fight Club', 'id': 1}]

How do I do that?

回答1:

In your BookSchema, you'll want to add a Nested authors field like you had (but commented out) but you'll want to specify that it will be a list by using the many keyword argument.

class BookSchema(ma.ModelSchema):

    # A list of author objects
    authors = ma.Nested(AuthorSchema, many=True)

    class Meta:
        model = Book