Search code examples
postgresqlfastapicascade

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.


Solution

  • 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.