[英]FastAPI Postgres Cascade Delete
I've 2 table, "Book" and "Bookmark".我有 2 张桌子,“书”和“书签”。
How to set a cascade on models so when they delete "Book", they will also delete "Bookmark" based on "Book".如何在模型上设置级联,以便当他们删除“Book”时,他们也会删除基于“Book”的“Bookmark”。
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:感谢 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")
I've add the cascade
to the relation
on the parent table, NOT the child table.我已将cascade
添加到父表上的relation
,而不是子表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.