pythondjangodjango-modelsdjango-signals

Prevent delete in Django model


I have a setup like this (simplified for this question):

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

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

When an Employee is about to get deleted, I want to check whether or not he is connected to any projects. If so, deletion should be impossible.

I know about signals and how to work them. I can connect to the pre_delete signal, and make it throw an exception like ValidationError. This prevents deletion but it is not handled gracefully by forms and such.

This seems like a situation that other will have run into. I'm hoping someone can point out a more elegant solution.


Solution

  • 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.