我有一个具有类似关系的 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"
被删除),但这并没有似乎发生在这里。
有人对可能发生的事情有任何想法吗?