Django阻止删除模型实例

2024-06-12 08:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型。模型表示mysql数据库视图的子类(即managed=False)。在

但是,在运行单元测试时,我得到:

DatabaseError: (1288, 'The target table my_view_table of the DELETE is not updatable')

这个删除请求的来源是(间接地)通过一个外键。我已经(简化):

class MyViewModel(models.Model):
    problematic_field = models.ForeignKey(ActualTableModel) # specifying on_delete=models.SET_NULL simply replaces the DELETE error with an UPDATE one

在我的测试的拆卸过程中,我正在删除ActualTableModel实例,并且django似乎遵循了文档化的行为:

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

当应用于(managed=False)视图时,这似乎会导致问题。在

我已尝试重写delete方法以阻止删除:

^{pr2}$

但这并没有解决问题。在

我怎样才能防止这种行为?在


Tags: ofthean视图falseobjectmodelswith