Overwrited delete method doesn't work when cascading delete

I have an application which simulates the comportment and arborescence of xml balises.

My first model, IdBalise, is used to link parents with children. It is linked with diferent balise models with a GenericForeignKey :

class IdBalise(models.Model):
    idBalise=models.AutoField(primary_key=True)

    parent = models.ForeignKey('IdBalise', on_delete=models.CASCADE, related_name="parentbal", null=True, blank=True)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

I use then many balise models like the one below :

class BiblBalise(Balise):
    idbal = GenericRelation(IdBalise, content_type_field="content_type", object_id_field="object_id", on_delete=models.CASCADE)  
    baliseName='bibl'

In order to delete the balise content when I delete an IdBalise, I overwrited the delete method of IdBalise :

def delete(self):
        self.content_object.delete()
        super(IdBalise, self).delete()

It works perfectly. When I delete an IdBalise, its related content (for instance, the entry in BiblBalise) is deleted.

My problem is, when I delete a parent, the children's content doesn't delete. The children IdBalise are deleted, because of the on_delete=models.CASCADE on the "parent" field. But their content (for instance, the entry in BiblBalise) isn't deleted.

Why my overwrited delete method doesn't work when the children IdBalise is deleted ? Any ideas ?

Thanks

Upvotes: 1

Views: 562

Answers (1)

dirkgroten
dirkgroten

Reputation: 20682

Late answer but I was looking at the same problem and noticed the Django documentation 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.

So basically you should use write a signal handler for pre_delete in your case.

Upvotes: 2

Related Questions