我在级联删除时遇到问题。我有两张 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/