gpt4 book ai didi

python - 如果删除了子项,则删除父项

转载 作者:行者123 更新时间:2023-12-02 11:18:59 26 4
gpt4 key购买 nike

如果子表中的关联行已被删除,我想删除父行。

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)
如果我移除 child
child_obj = session.query(Child).first()
session.delete(child_obj)
session.commit()
它确实删除了子对象,但父对象保持原样。我也想使用级联删除父级。

最佳答案

你可以阅读这个线程:
Linking Relationships with Backref

class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)

addresses = relationship("Address", backref="user")

class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
email = Column(String)
user_id = Column(Integer, ForeignKey('user.id'))
你可以在你的子类中定义它:
parent = relationship(Parent, backref=backref("children", cascade="all,delete"))

关于python - 如果删除了子项,则删除父项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com