首页 > 解决方案 > 删除子实体而不在 SQLAlchemy 中将 parent_id 设置为 NULL

问题描述

如果我们有两个 sqlalchemy 模型,其中一个子模型具有删除标志:


class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)

    children = relationship('Child', primaryjoin='and_(Parent.id==Child.parent_id, not_(Child.is)deleted))')


class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForegnKey('parent.id'), nullable=False)
    is_deleted = Column(Boolean, default=False)

    parent = relationship(Parent)

child当我从中删除parent时:

parent.children.remove(child)

SQLAlchemy 设置child.parent_id为 NULL。有没有办法从父母的children名单中删除孩子,但保留parent_id?现在我做:

child.is_deleted = True
session.flush()
session.refresh(parent)

child从列表中删除children,但也许有更好的方法?

标签: pythonsqlalchemy

解决方案


我不这么认为,只要你的关系依赖于 Child.parent_id。


推荐阅读