首页 > 解决方案 > SQLAlchemy 级联删除-孤儿不删除孤儿

问题描述

我有一个关系类似的 SQLAlchemy 模型

class Parent:
    
    children = relationship("Child", back_populates="parent", passive_deletes=True, cascade="all, delete-orphan")


class Child:
    
    parent_id = Column(
        Integer,
        ForeignKey(
            "parent.id",
            deferrable=True,
            initially="IMMEDIATE",
            ondelete="NO ACTION",
        ),
        nullable=False,
    )
    parent = relationship("Parent", back_populates="child")

但我发现数据并不总是孤立的。例如:

p = Parent()
p.children = [Child(parent=p))]
db.session.commit()

p.children = [Child(parent=p)]

print('before commit', p.children)
db.session.commit()
print('after commit', p.children)

输出

before commit [Child<transient>]

after commit [Child<1>, Child<2>]

根据我读过的文档,我希望这样做p.children = [Child]会孤立前一个p.children(然后让他们通过 删除cascade="all, delete-orphan"),但这似乎不会在这里发生。

有没有人对可能发生的事情有任何想法?

标签: pythonsqlalchemy

解决方案


推荐阅读