title: Flask Marshmallow/SqlAlchemy: Serializing many-to-many relationships
body: <p>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. </p>
  
  <p>Here is a simple example, more or less copy/pasted from flask-marshmallow docs:</p>
  
  <pre><code>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) &lt;-- 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)
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>print(Book.query.filter(1==1).options(joinedload('authors')).all()[0].authors)
  //--&gt; [&lt;__main__.Author object at 0x1043a0dd8&gt;]
  
  print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data)
  //--&gt; [{'authors': [1], 'title': 'Fight Club', 'id': 1}]
  </code></pre>
  
  <p>This is the result I want:</p>
  
  <pre><code>print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data)
  //--&gt; [{'authors': [{'name':'Chuck Paluhniuk', 'id':'1'}], 'title': 'Fight Club', 'id': 1}]
  </code></pre>
  
  <p>How do I do that?</p>