我有与"Basic Relationship Pattern One-To-Many" in the SQLAlchemy documentation.
类似的父表和子表class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship("Parent", back_populates="children")
我想从Child
中移除Parent
,但请将child.parent_id
设置为原始父级。
>>> parent = Parent()
>>> child = Child()
>>> parent.children.append(child)
>>> db.session.commit()
>>> assert child.parent_id == 1
>>> parent.children.remove(child)
>>> db.session.commit()
>>> assert len(parent.children) == 0
>>> assert child.parent_id == 1
这可以在不修改这些表的列的情况下实现吗?