[Django]-Prevent delete in Django model

21👍

For those referencing this questions with the same issue with a ForeignKey relationship the correct answer would be to use Djago’s on_delete=models.PROTECT field on the ForeignKey relationship. This will prevent deletion of any object that has foreign key links to it. This will NOT work for for ManyToManyField relationships (as discussed in this question), but will work great for ForeignKey fields.

So if the models were like this, this would work to prevent the deletion of
any Employee object that has one or more Project object(s) associated with it:

class Employee(models.Model):
    name = models.CharField(name, unique=True)

class Project(models.Model):
    name = models.CharField(name, unique=True)
    employees = models.ForeignKey(Employee, on_delete=models.PROTECT)

Documentation can be found HERE.

31👍

I was looking for an answer to this problem, was not able to find a good one, which would work for both models.Model.delete() and QuerySet.delete(). I went along and, sort of, implementing Steve K’s solution. I used this solution to make sure an object (Employee in this example) can’t be deleted from the database, in either way, but is set to inactive.

It’s a late answer.. just for the sake of other people looking I’m putting my solution here.

Here is the code:

class CustomQuerySet(QuerySet):
    def delete(self):
        self.update(active=False)


class ActiveManager(models.Manager):
    def active(self):
        return self.model.objects.filter(active=True)

    def get_queryset(self):
        return CustomQuerySet(self.model, using=self._db)


class Employee(models.Model):
    name = models.CharField(name, unique=True)
    active = models.BooleanField(default=True, editable=False)

    objects = ActiveManager()

    def delete(self):
        self.active = False
        self.save()

Usage:

Employee.objects.active() # use it just like you would .all()

or in the admin:

class Employee(admin.ModelAdmin):

    def queryset(self, request):
        return super(Employee, self).queryset(request).filter(active=True)
👤Elwin

12👍

This would wrap up solution from the implementation in my app. Some code is form LWN’s answer.

There are 4 situations that your data get deleted:

  • SQL query
  • Calling delete() on Model instance: project.delete()
  • Calling delete() on QuerySet innstance: Project.objects.all().delete()
  • Deleted by ForeignKey field on other Model

While there is nothing much you can do with the first case, the other three can be fine grained controlled.
One advise is that, in most case, you should never delete the data itself, because those data reflect the history and usage of our application. Setting on active Boolean field is prefered instead.

To prevent delete() on Model instance, subclass delete() in your Model declaration:

    def delete(self):
        self.active = False
        self.save(update_fields=('active',))

While delete() on QuerySet instance needs a little setup with a custom object manager as in LWN’s answer.

Wrap this up to a reusable implementation:

class ActiveQuerySet(models.QuerySet):
    def delete(self):
        self.save(update_fields=('active',))


class ActiveManager(models.Manager):
    def active(self):
        return self.model.objects.filter(active=True)

    def get_queryset(self):
        return ActiveQuerySet(self.model, using=self._db)


class ActiveModel(models.Model):
    """ Use `active` state of model instead of delete it
    """
    active = models.BooleanField(default=True, editable=False)
    class Meta:
        abstract = True

    def delete(self):
        self.active = False
        self.save()

    objects = ActiveManager()

Usage, just subclass ActiveModel class:

class Project(ActiveModel):
    ...

Still our object can still be deleted if any one of its ForeignKey fields get deleted:

class Employee(models.Model):
    name = models.CharField(name, unique=True)

class Project(models.Model):
    name = models.CharField(name, unique=True)
    manager = purchaser = models.ForeignKey(
        Employee, related_name='project_as_manager')

>>> manager.delete() # this would cause `project` deleted as well

This can be prevented by adding on_delete argument of Model field:

class Project(models.Model):
    name = models.CharField(name, unique=True)
    manager = purchaser = models.ForeignKey(
        Employee, related_name='project_as_manager',
        on_delete=models.PROTECT)

Default of on_delete is CASCADE which will cause your instance deleted, by using PROTECT instead which will raise a ProtectedError (a subclass of IntegrityError). Another purpose of this is that the ForeignKey of data should be kept as a reference.

👤anhdat

5👍

If you know there will never be any mass employee delete attempts, you could just override delete on your model and only call super if it’s a legal operation.

Unfortunately, anything that might call queryset.delete() will go straight to SQL:
http://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects

But I don’t see that as much of a problem because you’re the one writing this code and can ensure there are never any queryset.delete() on employees. Call delete() manually.

I hope deleting employees is relatively rare.

def delete(self, *args, **kwargs):
    if not self.related_query.all():
        super(MyModel, self).delete(*args, **kwargs)

4👍

I would like to propose one more variation on LWN and anhdat’s answers wherein we use a deleted field instead of an active field and we exclude “deleted” objects from the default queryset, so as to treat those objects as no longer present unless we specifically include them.

class SoftDeleteQuerySet(models.QuerySet):
    def delete(self):
        self.update(deleted=True)


class SoftDeleteManager(models.Manager):
    use_for_related_fields = True

    def with_deleted(self):
        return SoftDeleteQuerySet(self.model, using=self._db)

    def deleted(self):
        return self.with_deleted().filter(deleted=True)

    def get_queryset(self):
        return self.with_deleted().exclude(deleted=True)


class SoftDeleteModel(models.Model):
    """ 
    Sets `deleted` state of model instead of deleting it
    """
    deleted = models.NullBooleanField(editable=False)  # NullBooleanField for faster migrations with Postgres if changing existing models
    class Meta:
        abstract = True

    def delete(self):
        self.deleted = True
        self.save()

    objects = SoftDeleteManager()


class Employee(SoftDeleteModel):
    ...

Usage:

Employee.objects.all()           # will only return objects that haven't been 'deleted'
Employee.objects.with_deleted()  # gives you all, including deleted
Employee.objects.deleted()       # gives you only deleted objects

As stated in anhdat’s answer, make sure to set the on_delete property on ForeignKeys on your model to avoid cascade behavior, e.g.

class Employee(SoftDeleteModel):
    latest_project = models.ForeignKey(Project, on_delete=models.PROTECT)

Note:

Similar functionality is included in django-model-utils‘s SoftDeletableModel as I just discovered. Worth checking out. Comes with some other handy things.

2👍

I have a suggestion but I’m not sure it is any better than your current idea. Taking a look at the answer here for a distant but not unrelated problem, you can override in the django admin various actions by essentially deleting them and using your own. So, for example, where they have:

def really_delete_selected(self, request, queryset):
    deleted = 0
    notdeleted = 0
    for obj in queryset:
        if obj.project_set.all().count() > 0:
            # set status to fail
            notdeleted = notdeleted + 1
            pass
        else:
            obj.delete()
            deleted = deleted + 1
    # ...

If you’re not using django admin like myself, then simply build that check into your UI logic before you allow the user to delete the object.

0👍

For anyone who finds this and wants to know how you can add PROTECT to you model fields, but have it ignore any soft deleted objects, you can do this by simply overriding the PROTECT that comes with Django:

def PROTECT(collector, field, sub_objs, using):
if sub_objs.filter(deleted=False).count() > 0:
    raise ProtectedError(
        "Cannot delete some instances of model '%s' because they are "
        "referenced through a protected foreign key: '%s.%s'"
        % (
            field.remote_field.model.__name__,
            sub_objs[0].__class__.__name__,
            field.name,
        ),
        sub_objs.filter(deleted=False),
    )

This will check whether there are any objects that have not been soft deleted, and only return those objects in the error. This has not been optimized.

0👍

Can’t believe it’s been 10 years since I asked this question. A similar issue came up again, and we ended up packing our solution in a small toolkit we use internally. It adds a ProtectedModelMixin which is related to the question asked here. See https://github.com/zostera/django-marina

👤dyve

0👍

I had the same problem and just found a great solution for this.

There are two ways that someone can try to delete your model instances: by deleting an instance or by calling delete on an entire queryset. You don’t need to worry about someone calling delete on the manager because the delete method is not exposed in the manager. To quote Django docs:

Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
Entry.objects.all().delete()

To prevent instance-level deletion, you can simply override the delete method in your model class:

from django.db import models

class Undeletable(models.Model):
    # your fields here

    def delete(self, using=None, keep_parents=False):
        raise models.ProtectedError("You can't delete this model!", self)

Now onto the next concern: queryset deletions. To tackle this problem, we need to know a few things about Django:

  • When you call a method on a queryset that creates another queryset, for example queryset.filter() or queryset.exclude(), a new queryset is created, but its type is the same as the type of the older queryset. So if queryset q is an instance of MyQuerySet, q.filter(#filters) will create a new object of type MyQuerySet
  • The models.Manager class which is the default manager for models.Model classes, has an attribute _queryset_class that determines what kind of queryset is returned from methods like .all() or .filter()
  • In order to create a manager class with a custom _queryset_class, you can look at the source code for models.Manager class, which is the default manager for models.Model classes:
class Manager(BaseManager.from_queryset(QuerySet)):
    pass

So, in order to prevent querysets from bulk-deleting our model, we can use the following code:

from django.db import models

class UndeletableQueryset(models.QuerySet):
    def delete(self):
        raise models.ProtectedError("You can't delete this model!", self)

class Undeletable(models.Model):
    objects = models.manager.BaseManager.from_queryset(UndeletableQueryset)()
    
    # your fields here

    def delete(self, using=None, keep_parents=False):
        raise models.ProtectedError("You can't delete this model!", self)

And just like that, you have blocked all the ways that your model instances can be deleted, and on top of that you raise an error whenever someone tries to delete them.

Note how this behavior is preserved through the chaining of filters and excludes because each queryset that is returned is still an instance of UndeletableQueryset which overrides the delete method.

Leave a comment