问题描述
我有两个表(多对多)映射到 sqlAlchemy 并配置了删除级联选项。
它工作正常,但我想改变一种行为。
实际行为
当我删除一个实体时,通过级联,该实体下的所有用户都将被删除。
+-------------+----------------------+
| id | entities |
+-------------+----------------------+
| 1 | Entity_1 |
| 2 | Entity_2 |
+-------------+----------------------+
+-------------+----------------------+
| id | users |
+-------------+----------------------+
| 1 | User_1 |
+-------------+----------------------+
+-------------+----------------------+
| entity_id | user_id |
+-------------+----------------------+
| 1 | 1 |
| 2 | 1 |
+-------------+----------------------+
当我删除实体 ID 2 时:
session.query(EntityModel).filter(EntityModel.id == 2).delete()
session.commit()
实际结果:
+-------------+----------------------+
| id | entities |
+-------------+----------------------+
| 1 | Entity_1 |
+-------------+----------------------+
+-------------+----------------------+
| id | users |
+-------------+----------------------+
+-------------+----------------------+
+-------------+----------------------+
| entity_id | user_id |
+-------------+----------------------+
+-------------+----------------------+
我不想要这种行为。
我需要从表实体中删除一个实体并删除您引用的用户,但是如果用户被两个(或多个)实体引用,我不想删除它,我只想删除引用表 entity_user 上,然后删除实体。
这在 sqlAlchemy 上可行吗? EntityModel 类的关系配置如何?
class EntityModel(Base):
__tablename__ = "entities"
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String,nullable=False)
users = relationship(
"usermodel",secondary="entity_user",back_populates="entities",cascade="all,delete",)
class usermodel(Base):
__tablename__ = "users"
id = Column(Integer,autoincrement=True)
name = Column(String)
entities = relationship(
"EntityModel",back_populates="users",uselist=True,lazy="joined",)
class Entityusermodel(Base):
__tablename__ = "entity_user"
__table_args__ = (PrimaryKeyConstraint("user_id","entity_id"),)
user_id = Column(Integer,ForeignKey("users.id"))
entity_id = Column(Integer,ForeignKey("entities.id"))
预期行为:
当我这样做时:
session.query(EntityModel).filter(EntityModel.id == 2).delete()
session.commit()
预期结果:
+-------------+----------------------+
| id | entities |
+-------------+----------------------+
| 1 | Entity_1 |
+-------------+----------------------+
+-------------+----------------------+
| id | users |
+-------------+----------------------+
| 1 | User_1 |
+-------------+----------------------+
+-------------+----------------------+
| entity_id | user_id |
+-------------+----------------------+
| 1 |1 |
+-------------+----------------------+
Entity 1 和 User 1 的关系避免了 User 1 会被删除。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)