最佳答案
对于 SQLAlchemy 的级联选项,我肯定遗漏了一些细节,因为我无法获得一个简单的级联 delete 来正确操作——如果父元素被删除了,那么子元素将使用 null
外键持久化。
我在这里放了一个简明的测试案例:
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Parent(Base):
__tablename__ = "parent"
id = Column(Integer, primary_key = True)
class Child(Base):
__tablename__ = "child"
id = Column(Integer, primary_key = True)
parentid = Column(Integer, ForeignKey(Parent.id))
parent = relationship(Parent, cascade = "all,delete", backref = "children")
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
parent = Parent()
parent.children.append(Child())
parent.children.append(Child())
parent.children.append(Child())
session.add(parent)
session.commit()
print "Before delete, children = {0}".format(session.query(Child).count())
print "Before delete, parent = {0}".format(session.query(Parent).count())
session.delete(parent)
session.commit()
print "After delete, children = {0}".format(session.query(Child).count())
print "After delete parent = {0}".format(session.query(Parent).count())
session.close()
产出:
Before delete, children = 3
Before delete, parent = 1
After delete, children = 3
After delete parent = 0
父母和孩子之间有一种简单的一对多的关系。该脚本创建一个父代,添加3个子代,然后提交。接下来,它删除父级,但子级保留。为什么?我如何使孩子级联删除?