python - 删除子实体而不在 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
,但也许有更好的方法?
解决方案
我不这么认为,只要你的关系依赖于 Child.parent_id。
推荐阅读
- python - 如何在 matplotlib 散点图中绘制相关线?
- sql-server - SSIS - SQL Server 2016 的 Sharepoint 列表适配器
- regex - 需要一个正则表达式,其中两个不同的子字符串不能包含在一个字符串中
- powershell - Powershell问题比较并将其保存为文本文件
- r - 使用 optim() 进行抛物线插值
- kubernetes - 如何从图像拉取阶段发生错误导致的“待处理”状态中解开 Pod
- python - 按升序对熊猫列进行排序,然后对非 0 重复项进行排序
- peoplesoft - 如何使用单选按钮进行人员编码
- azure - Azure VM 上的 Azure Pipelines 代理
- android - BufferKnife 在构建 gradle Android Studio 时产生问题