Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overridden delete method of child model does not get called when deleting parent?

Tags:

django

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?

like image 332
WesDec Avatar asked Jan 20 '12 16:01

WesDec


1 Answers

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.

like image 199
aganders3 Avatar answered Sep 23 '22 12:09

aganders3