繁体   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