I must be missing something trivial with SQLAlchemy\'s cascade options because I cannot get a simple cascade delete to operate correctly -- if a parent element is a deleted,
@Steven's asnwer is good when you are deleting through session.delete()
which never happens in my case. I noticed that most of the time I delete through session.query().filter().delete()
(which doesn't put elements in the memory and deletes directly from db).
Using this method sqlalchemy's cascade='all, delete'
doesn't work. There is a solution though: ON DELETE CASCADE
through db (note: not all databases support it).
class Child(Base):
__tablename__ = "children"
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey("parents.id", ondelete='CASCADE'))
class Parent(Base):
__tablename__ = "parents"
id = Column(Integer, primary_key=True)
child = relationship(Child, backref="parent", passive_deletes=True)