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):However, the
pre_deleteandpost_deletesignals 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.