SQLAlchemy: cascade delete

后端 未结 9 1554
星月不相逢
星月不相逢 2020-11-28 01:07

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,

9条回答
  •  遥遥无期
    2020-11-28 01:37

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

提交回复
热议问题