簡體   English   中英

SQLAlchemy:多個表的外鍵

[英]SQLAlchemy: foreign key to multiple tables

讓我們考慮 3 個表:

  • 圖書
  • 美國作家
  • 英國作家

每本書都有一個指向其作者的外鍵,可以在美國表中,也可以在英國表中。

如何在 SQLAlchemy 中實現這樣的外鍵條件?

我想要一列來處理鏈接。


到目前為止,我的方法是創建一個抽象類AuthorAmericanAuthorBritishAuthorBritishAuthor繼承,並且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是抽象的......

我認為您不能使用同一列與兩個不同的表建立關系。

嘗試創建兩個不同的列(“american_author_id”和“british_author_id”),然后創建一個@property“author”,返回不為 NULL 的作者。

通過這種方式,您可以使用以下方法獲取作者: mybook.author

雖然@property裝飾將在申請工作,它可能是最好使用@hybrid_propertysqlalchemy.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM