I believe this issue is addressed in the docs
where it says:
Overridden model methods are not called on bulk operations
Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.
Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called.
As suggested in the docs above, I believe a better solution is to use the post_delete
signal, like so:
from django.db.models.signals import post_delete
from django.dispatch import receiver
class Image(models.Model):
img = models.ImageField(upload_to=get_image_path)
...
@receiver(post_delete, sender=Image)
def delete_image_hook(sender, instance, using, **kwargs):
instance.img.delete()
Unlike overriding the delete
method, the delete_image_hook
function should be called on bulk deletes and cascading deletes as well. Here is more information on using Django's Signals: https://docs.djangoproject.com/en/1.11/topics/signals/#connecting-to-signals-sent-by-specific-senders
Note on previous answers:
Some of the earlier posts suggest overriding the delete
method of QuerySet, which may have performance implications and other unintended behavior. Perhaps those answers were written before Django's Signals were implemented, but I think using Signals is a cleaner approach.