Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 631
sapi Avatar asked Jan 24 '13 01:01

sapi


People also ask

What is__ str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How to disable delete in Django admin?

You need to add a new method has_delete_permission in the Admin class where you want to disable the delete function.

What is deferred attribute Django?

A deferred attribute is an attribute that derives its value from an attribute value on a different account. You declare the deferred attribute in a view (and the WSUser model), and the provisioning engine performs this substitution immediately before calling the adapter.

What is get_ absolute_ url in Django?

get_absolute_url allows to keep your object DRY. To have a url which defines that object instance. In most case a detail page for that object.


1 Answers

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

Ie.:

problematic_field = models.ForeignKey(ActualTableModel, on_delete=models.PROTECT)
like image 134
jpic Avatar answered Sep 19 '22 01:09

jpic