简体   繁体   中英

FastAPI Postgres Cascade Delete

I've 2 table, "Book" and "Bookmark".
How to set a cascade on models so when they delete "Book", they will also delete "Bookmark" based on "Book".

Here's the models:

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")

Please help, thanks.

Thanks to MatsLindh, here's the correct answer:

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")

I've add the cascade to the relation on the parent table, NOT the child table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM