[Answer]-Deny deletion of model if it is referenced in a ManyToMany Relationship

1👍

I believe the correct way is to hook on the pre_delete signal.

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.')
👤Todor

0👍

Simplest approach will be to override the delete() method of Meal model.

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)
👤xyres

Leave a comment