通用的解決方案要刪除的不作爲外鍵通用的解決方案要刪除的不作爲外鍵
這裏有預設,有多種型號記錄記載:「ParentA」,「ParentB」,」 ChildAA','ChildBA'等。
ParentX和ChildXY之間的關係是ChildXY有ParentX, 的例如一個外鍵:
#this is ParentA
class ParentA(Base):
__tablename__ = 'parenta'
id = Column(Integer, primary_key=True)
name = Column(String(12))
need_delete = Column(Integer)
children = relationship("ChildAA",
back_populates="parent")
#this is ChildAA
class ChildAA(Base):
__tablename__ = 'childaa'
name = Column(String(12))
id = Column(Integer, primary_key=True)
need_delete = Column(Integer)
parenta_id = Column(Integer, ForeignKey('parenta.id'))
parenta = relationship("ParentA")
#this is ParentB
........
而且我想刪除所有記錄(所有childx,parentx包括在內),其屬性「need_delete」是1並且記錄自己沒有被用作子表的外鍵。我發現了一個直接的,但複雜的方式:
我可以先通過所有的childx表和安全removd記錄,然後到parentx表和一個刪除與 代碼塊一個記錄:
#deletion is for ParentA
for parent in session.query(ParentA).join(ParentA.children).group_by(ParentA).having(func.count(ChildAA.id) == 0):
if parent.need_delete == 1
session.delete(parent)
#deletion is for ParentB
......
#deletion is for ParentC
.....
session.commit()
這是硬編碼,是否有任何通用的方式來刪除當前用作外鍵的記錄?
@ IljaEverilä,謝謝,我更新了這個問題〜 – TommyLike
另一個問題是,所有的「父母」模型都將關係定義爲「children」屬性嗎? –
@IljaEverilä,是的,他們都有一個表明這一點,但他們的屬性名稱不同於childrenx,childreny .... – TommyLike