flask - 如何定义 sqlalchemy 多对多关系

标签 flask sqlalchemy flask-sqlalchemy

我正在使用 Flask 和 sqlalchemy 编写一个项目。

我正在尝试创建一个数据库,其中作者有很多书籍。

为此目的我写道:

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


class Books(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.Integer, db.ForeignKey('author.id'))

第一个问题:这是正确的方法吗?

第二个问题:我想知道每个作者写了哪些书 - 我该怎么做?

第三个问题:假设每本书都可以由很多作者写, 我如何知道哪些作者写了某本书?

我提前感谢

最佳答案

first question: is it the correct way to do it?

几乎是正确的。您还应该创建一个中间模型来存储实际关系。因为它是many-to-many relationship ,它需要第三个表来操作。

second question: i want to know which books each author wrote - how can i do it?

third question: lets say that each book can be written by a lot of authors, how can i know which authors wrote a certain book?

您可以使用 SQLAlchemy 的 association proxy 轻松实现它.

类似的事情:

from myapp import db

from sqlalchemy.ext.associationproxy import association_proxy


class Book(db.Model):
    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(60))

    # access all authors of that book
    authors = association_proxy('bookauthor', 'author', creator=lambda author: BookAuthor(author=author))

    def __init__(self, title):
        self.title = title

    def __unicode__(self):
        return '<Book {0}>'.format(self.id)


class Author(db.Model):
    __tablename__ = 'author'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))

    # access all books w/ this author
    books = association_proxy('bookauthor', 'book', creator=lambda book: BookAuthor(book=book))

    def __init__(self, name):
        self.name = name

    def __unicode__(self):
        return '<Author {0}>'.format(self.id)


class BookAuthor(db.Model):
    """ This is an association table for the Book<->Author Many to Many relationship. """
    __tablename__ = 'book_author'

    id = db.Column(db.Integer, primary_key=True)

    id_book = db.Column(db.Integer, db.ForeignKey('book.id'), primary_key=True)
    id_author = db.Column(db.Integer, db.ForeignKey('author.id'), primary_key=True)

    # you can also access these objects of books and authors respectively
    book = db.relationship(Book, backref='bookauthor')
    author = db.relationship(Author, backref='bookauthor')

    def __unicode__(self):
        return '<BookAuthor {0}>'.format(self.id)

因此,您将能够使用以下方式访问该书的所有作者:

book = db.session.query(Book).filter_by(title="The Catcher in the Rye")
book.authors()
# [<Author 'J. D. Salinger'>]

关于flask - 如何定义 sqlalchemy 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301917/

相关文章:

python - Flask-Babel 不会翻译 Web 项目中的任何内容

python - 如何显示和下载位于静态文件夹之外的图像?

python - 如何为 SQLALCHEMY 配置找到 postgresql uri

python - 从 Flask-SQLAlchemy 获取 UTC 格式的日期时间字段

python - Heroku 上的 Flask 和 Celery : sqlalchemy. exc.DatabaseError : (psycopg2. DatabaseError) SSL 错误:解密失败或错误记录 mac

python - Flask + SQLAlchemy - 修改列 setter 的自定义元类(动态 hybrid_property)

python - 使用 flask 和外部上下文/cronjobs 发送电子邮件

python - 使用 python 从查询返回元组

python - SQLAlchemy 核心插入使( Pyramid )作用域 session 挂起

python - 让 pylint 在 pylons/SA 模型中查找继承方法时遇到问题