Prevent delete in Django model

后端 未结 6 822
醉酒成梦
醉酒成梦 2020-12-30 01:08

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

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

class Project(models.M         


        
6条回答
  •  执笔经年
    2020-12-30 01:55

    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.

提交回复
热议问题