1
下面是與backref和刪除級聯關係的簡單示例。如何使用sqlalchemy中的關係更改父項?
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('Parent.id'))
parent = relation(
'Parent',
backref=backref('children', cascade='delete, delete-orphan')
)
需要從一個父到另一個重新分配一些孩子,則需要刪除另一個父,但SQLAlchemy的父母刪除之前刪除的孩子......
p1 = Session.query(Parent).get(...)
p2 = Session.query(Parent).get(...)
p1.children.extend(p2.children)
Session.delete(p2)
Session.commit()
登錄:
... [worker 0] UPDATE child SET parent_id=%(parent_id)s WHERE child.id = %(child_id)s
...
... [worker 0] DELETE FROM child WHERE child.id = %(id)s
...
... [worker 0] DELETE FROM parent WHERE parent.id = %(id)s
...
... [worker 0] COMMIT
需要以某種方式將孩子從另一父母分離...