Ryan Saxe
Ryan Saxe

Reputation: 17829

Django disable model delete

So every model comes with some commonly used functions such as save and delete.

Delete is often overridden to set a boolean field such as is_active to false, this way data is not lost. But sometimes a model exists that has information that, once created, should always exist and never even be "inactive". I was wondering what the best practice for handling this model's delete method would be?

ideas

make it simply useless:

def delete(self):
    return False

but that just seems odd. Is there maybe a Meta option to disable deleting? is there any "nice" way to do this?

Upvotes: 7

Views: 1831

Answers (2)

Sergey Geron
Sergey Geron

Reputation: 10152

delete() on queryset can be restricted with this:

class NoDeleteQuerySet(models.QuerySet):
    def delete(self, *args, **kwargs):
        pass

class MyModel(models.Model):
    objects = NoDeleteQuerySet.as_manager()
    ...

Django docs - link

Upvotes: 0

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 32394

Well it depends, you cannot truly restrict deletion, because somebody can always call delete() on queryset or just plain DELETE sql command. If you want to disable delete button in django admin though, you should look here.

Upvotes: 2

Related Questions