我有一个包含作者和书籍的数据库。一位作者可以有多本书,而一本书可以有多位作者,所以要多对多。目标是拥有一个使用sqlalchemy和棉花糖的REST API:
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):
__tablename__ = 'author'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
class Book(db.Model):
__tablename__ = 'book'
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, many=True)
class Meta:
model = Book
现在,我添加一些作者和书籍:
authors_schema = AuthorSchema(many=True)
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()
book1 = Book(title='Lord of the Rings')
book1.authors.append(author)
db.session.add(book1)
db.session.commit()
s = BookSchema(many=True)
a = AuthorSchema(many=True)
author1 = Author(name='Tolkien')
book1.authors.append(author1)
db.session.commit()
现在,我要打印所有作者及其书籍:
authors = Author.query.all()
print(authors_schema.dump(authors))
[{'books': [1, 2], 'id': 1, 'name': u'Chuck Paluhniuk'}, {'books': [2], 'id': 2, 'name': u'Tolkien'}]
但是,我想直接显示书名而不是ID,例如:
[{'books': ['Fight Club', 'Lord of the Rings'], 'id': 1, 'name': u'Chuck Paluhniuk'}, {'books': ['Lord of the Rings'], 'id': 2, 'name': u'Tolkien'}]