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.
For those referencing this questions with the same issue with a
ForeignKeyrelationship the correct answer would be to use Djago'son_delete=models.PROTECTfield on theForeignKeyrelationship. This will prevent deletion of any object that has foreign key links to it. This will NOT work for forManyToManyFieldrelationships (as discussed in this question), but will work great forForeignKeyfields.So if the models were like this, this would work to prevent the deletion of any
Employeeobject that has one or moreProjectobject(s) associated with it:Documentation can be found HERE.