Prevent delete in Django model

后端 未结 6 769
醉酒成梦
醉酒成梦 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

    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)
    

提交回复
热议问题