sapi
sapi

Reputation: 10224

django prevent delete of model instance

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, '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

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

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.

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

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

but that did not solve the problem.

How can I prevent this behaviour?

Upvotes: 6

Views: 6226

Answers (1)

jpic
jpic

Reputation: 33420

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

Ie.:

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

Upvotes: 10

Related Questions