如果在ManyToMany关系中引用模型,则拒绝删除模型

时间:2015-04-12 09:58:33

标签: django django-models

我有以下模特:

class Meal(models.Model):
    name_text = models.CharField(max_length=200)

class Menu(models.Model):
    meals = models.ManyToManyField(Meal)

当我删除一顿饭时,我想提出一条错误消息,例如"你不能删除这顿饭,因为它是在菜单中使用的,当菜单中引用了这顿饭时。

在我致电meal.delete()时,这顿饭刚被删除。 ManyToMany-Relationships的on_deleted属性是否与ForeignKey关系类似?

或者我是否必须浏览所有Menu并检查是否有人引用meal

2 个答案:

答案 0 :(得分:0)

最简单的方法是覆盖delete()模型的Meal方法。

class Meal(models.Model):
    name_text = models.CharField(max_length=200)

    def delete(self, *args, **kwargs):
        # count the total menus this meal is used in
        if self.menu_set.count() >  0:
            return "Can not delete this menu"
        else:
            super(Meal, self).delete(*args, **kwargs)

答案 1 :(得分:0)

我认为正确的方法是挂钩pre_delete信号。

from django.db.models.signals import pre_delete
from django.dispatch import receiver
from myapp.models import Meal


@receiver(pre_delete, sender=Meal)
def on_meal_delete(sender, instance, **kwargs):
    if instance.menu_set.exists():
        raise ValueError('Cannot delete this meal. It has menus.')