django防止删除模型实例 [英] django prevent delete of model instance

查看:49
本文介绍了django防止删除模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个models.Model子类,它代表我的mysql数据库上的一个View(即managed = False)。

I have a models.Model subclass which represents a View on my mysql database (ie managed=False).

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

However, when running my unit tests, I get:


DatabaseError:(1288,'DELETE的目标表my_view_table无法更新')

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

此删除请求的来源是(间接)通过外键。我有(简体):

The source of this deletion request is (indirectly) via a foreign key. I have (simplified):

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似乎遵循了记录的行为:

During the tearDown of my tests, I am deleting the ActualTableModel instance, and it appears that django is following the documented behaviour:


当Django删除对象时,它会模仿SQL约束在DELETE CASCADE上的行为-换句话说,任何具有外键指向要删除对象的对象都将与其一起删除。

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)视图时,这似乎引起问题。

This seems to be causing problems when applied to the (managed=False) View.

我尝试覆盖delete方法以防止删除:

I have tried overriding the delete method to prevent deletion:

class MyViewModel(models.Model):
    ...
    def delete(self, *args, **kwargs):
        pass # deletion of a view row is never valid

但这不能解决问题。

如何防止这种行为?

推荐答案

也许您可以尝试以下一种方法各种 on_delete参数选项

Maybe you could try one of the various on_delete argument options ?

即。

problematic_field = models.ForeignKey(ActualTableModel, on_delete=models.PROTECT)

这篇关于django防止删除模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆