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.')
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)
- [Answer]-How to tell a Django view who called it?
- [Answer]-Sending A post request from ajax to a python function but receiving a GET request?
Source:stackexchange.com