Skip to content
Advertisement

In django, how to delete all related objects when deleting a certain type of instances?

I first tried to override the delete() method but that doesn’t work for QuerySet’s bulk delete method. It should be related to pre_delete signal but I can’t figure it out. My code is as following:

def _pre_delete_problem(sender, instance, **kwargs):
    instance.context.delete()
    instance.stat.delete()

But this method seems to be called infinitely and the program runs into a dead loop. Can someone please help me?

Advertisement

Answer

If the class has foreign keys (or related objects) they are deleted by default like a DELETE CASCADE in sql.

You can change the behavior using the on_delete argument when defining the ForeignKey in the class, but by default it is CASCADE. You can check the docs here.

Now the pre_delete signal works, but it doesn’t call the delete() method if you are using a bulk delete, since its not deleting in a object by object basis.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement