I need to call a function whenever I have an object of a model deleted via admin page. How can I do such thing?
CodePudding user response:
Yes, it's called a post_delete signal. Here is one way of doing it (you can add this to the bottom of your models.py file, or at least after your model:
from django.db.models.signals import post_delete
from django.dispatch import receiver
@receiver(post_delete, sender=YourModelName)
def signal_function_name(sender, instance, using, **kwargs):
your_function(args)
This function will be called AFTER the object is deleted. There are also pre_save, post_save, among other types of signals.
This signal will be called on delete from within the admin or ANY delete action anywhere (your other logic, views, the python shell, etc).
CodePudding user response:
def delete(self):
files = WidgetFile.objects.filter(widget=self)
if files:
for file in files:
file.delete()
super(Widget, self).delete()
This triggered the necessary delete() method on each of the related objects, thus triggering my custom file deleting code. It's more database expensive yes, but when you're trying to delete files on a hard drive anyway, it's not such a big expense to hit the db a few extra times.