SQLAlchemy:多个表的外键

时间:2019-07-15 13:26:40

标签: python postgresql sqlalchemy

让我们考虑3个表:

  • 美国作家
  • 英国作家

每本书的作者都有一个外键,可以在美国表中,也可以在英国表中。

如何在SQLAlchemy中实现这种外键条件?

我想用一列来处理链接。


到目前为止,我的方法是创建一个抽象类AuthorAmericanAuthorBritishAuthor都从中继承,并且将Book的外键指向父类

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

class AmericanAuthor(Author):
    __tablename__ = 'american_author'
    # some other stuff

class BritishAuthor(Author):
    __tablename__ = 'british_author'
    # some other stuff

class Book(Model):
    __tablename__ = 'book'
    title = db.Column(db.String)
    author_id = db.Column(db.Integer, db.ForeignKey("author.id"))

它失败并显示以下错误:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'books.author_id' could not find table 'author' with which to generate a foreign key to target column 'id'

考虑到author是抽象的,这完全有道理...

2 个答案:

答案 0 :(得分:3)

尽管@property装饰器将在应用程序中工作,但最好使用@hybrid_property包中的sqlalchemy.ext.hybrid。这样,您将可以像过滤任何普通属性一样对该属性进行过滤。

您的Book类将如下所示:

class Book(Model):
    __tablename__ = 'book'
    title = db.Column(db.String)
    american_author_id = db.Column(db.Integer, db.ForeignKey("american_author.id"), nullable=True)
    british_author_id = db.Column(db.Integer, db.ForeignKey("british_author.id"), nullable=True)

    @hybrid_property
    def author_id(self):
        return self.american_author_id or self.british_author_id

答案 1 :(得分:0)

我认为您不能使用同一列与两个不同的表建立关系。

尝试创建两个不同的列(“ american_author_id”和“ british_author_id”),然后创建一个@property“ author”,以返回不为NULL的作者。

通过这种方式,您可以使用mybook.author

相关问题