0

I have following models:

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

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

When I delete a meal I would like to raise an error message like "You can't delete this meal because it is used in a menu", when the meal is referenced in a menu.

At the moment when I call meal.delete() the meal is just deleted. Is there an on_deleted attribute for the ManyToMany-Relationships similar to the ForeignKey Relationship?

Or do I have to go through all Menus and check if one references the meal?

Sven
  • 1,648
  • 1
  • 21
  • 31
  • possible duplicate of [Prevent delete in Django model](http://stackoverflow.com/questions/4825815/prevent-delete-in-django-model) – dting Apr 12 '15 at 10:11

2 Answers2

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
  • 20,487
  • 3
  • 56
  • 85
0

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
  • 15,307
  • 5
  • 55
  • 62