簡體   English   中英

FastAPI Postgres 級聯刪除

[英]FastAPI Postgres Cascade Delete

我有 2 張桌子,“書”和“書簽”。
如何在模型上設置級聯,以便當他們刪除“Book”時,他們也會刪除基於“Book”的“Bookmark”。

這是模型:

class Book(Base):
    __tablename__ ="book"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)

    # relation
    r_bookmark = relationship("BookMark", back_populates="r_book")


class BookMark(Base):
    __tablename__ ="bookmark"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)
    book_id = Column(Integer, ForeignKey("book.id", ondelete='CASCADE'), nullable=False)

    # relation
    r_book = relationship("Book", back_populates="r_bookmark", cascade="all,delete")

請幫忙,謝謝。

感謝 MatsLindh,這是正確的答案:

class Book(Base):
    __tablename__ ="book"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)

    # relation
    r_bookmark = relationship("BookMark", back_populates="r_book", cascade="all,delete")


class BookMark(Base):
    __tablename__ ="bookmark"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)
    book_id = Column(Integer, ForeignKey("book.id"), nullable=False)

    # relation
    r_book = relationship("Book", back_populates="r_bookmark")

我已將cascade添加到父表上的relation ,而不是子表。

暫無
暫無

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

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