sqlalchemy - 将删除级联到多对多关联表?

标签 sqlalchemy

我在级联删除时遇到问题。我有两张 table ,它们
多对多映射:

class File(object): pass 
file_table = Table('file', metadata, 
        Column('id', Integer, primary_key=True, autoincrement=True), 
        Column('filename', String(255)), 
} 

class FileHost(object): pass 
file_host = Table('host', metadata, 
        Column('id', Integer, primary_key=True, autoincrement=True ), 
        Column('name', String(255)), 
) 

file_hosted = Table('file_hosted', metadata, 
        Column('id_host', Integer, ForeignKey('host.id')), 
        Column('id_file', Integer, ForeignKey('file.id')) 
) 

session.mapper(File, file_table, properties={ 
    'host': relation(FileHost, secondary=file_hosted, backref='files', 
                        cascade='all,delete-orphan', single_parent=True) 
}) 
session.mapper(FileHost, file_host) 

这是我得到的错误:
sqlalchemy.exc.IntegrityError: 
(IntegrityError) update or delete on table "file" violates
foreign key constraint "file_hosted_id_file_fkey" on table "file_hosted" 
DETAIL:  Key (id)=(50905) is still referenced from table "file_hosted". 

有没有人知道我做错了什么?

我也问了问题on the sqlalchemy mailing list ,并得到正确答案:

You are telling SQLAlchemy to cascade File deletes to FileHost, but you want it the other way around. You can fix this by moving the cascade='all,delete-orphan' and single_parent=True clauses into the backref. You also probably want uselist=False.


session.mapper(File, file_table, properties={ 
    'host': relation(FileHost, 
                     backref=backref('files', 
                                     cascade='all,delete-orphan', 
                                     single_parent=True), 
                     secondary=file_hosted, 
                     uselist=False) 
}) 

最佳答案

应该注意的是,虽然在这种特殊情况下这不是问题,但如果您不包含 ondelete="CASCADE",您仍然可能会收到此错误。在您的外键声明中。即使在声明 cascade="all,delete" 之后在我的人际关系中,在添加 ondelete 之前,我仍然收到此错误。属性。您可能想添加 onupdate="CASCADE"以及。

关于sqlalchemy - 将删除级联到多对多关联表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232391/

相关文章:

python - 在 sqlalchemy 中设置 server_default 失败

python - 使用 sqlalchemy-cockroachdb 时导入作业消失

python - SQLAlchemy 连接在 AWS MySQL RDS 重启时挂起并进行故障转移

python - 如何使用 GROUP BY 和 HAVING 与 SQLAlchemy 和 Postgresql 获取具有最大更新日期时间的行

python - SQLAlchemy 急切加载多个关系

python - Pyodbc + sqlalchemy 超过 2100 个项目失败

python - 分配给未映射到 SQLAlchemy 列的属性时如何引发异常?

python - 如何使用 Flask/SqlAlchemy/SQLite 对过去 7 天的每一天的数据库记录进行分组?

python - 映射递归关系时出现问题 - SQLAlchemy

python - 如何在 sqlalchemy 中获取 backref 名称?