I have a two models, each with an image. One has a foreign key to the parent. When I delete the parent I want to delete the parent and child along with their image file on the disk. To do that I override the delete method:
class MyModelParent(models.Model):
image = models.ImageField(upload_to = "images/" )
def delete(self, *args, **kwargs):
if self.image:
self.image.delete()
super(MyModelParent, self).delete(*args, **kwargs)
class MyModelChild(models.Model):
parent = models.ForeignKey(MyModelParent)
image = models.ImageField(upload_to = "images/" )
def delete(self, *args, **kwargs):
if self.image:
self.image.delete()
super(MyModelChild, self).delete(*args, **kwargs)
When I delete an instance of MyModelParent, its overridden delete() gets called, but not the ones of the children (even though they get deleted from the DB), so their images remain on the disk. Anyone know what I am doing wrong?
You're not doing anything wrong. The problem is that the delete()
method of any child is not called when cascading.
From the documentation for delete
(cascaded delete uses the database query):
The delete() method does a bulk delete and does not call any delete() methods on your models. It does, however, emit the pre_delete and post_delete signals for all deleted objects (including cascaded deletions).
However, the pre_delete
and post_delete
signals are still sent. What you need to do is connect a callback that will listen for one of these signals and do any extra cleanup needed.
See the relevant documentation for more information on connecting signals
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With