[Django]-Delete parent object when child object is deleted in Django

3👍

You should use signals.

@receiver(post_delete, sender=B)
def delete_a(sender, instance, **kwargs):
     # instance.type_b is the object which you want to delete

2👍

A best way to do it, just add [on_delete=models.CASCADE][1]

:

class A(models.Model):
    name = models.CharField(max_length=128)

class B(modes.Model):
    type_b = models.ForeignKey(A,on_delete=models.CASCADE)

0👍

You can use post_delete signal to delete the parent as suggested by Davit Tovmasyan.

BUT because of the cascading nature as the parent A object is deleted, it will also delete all the connected B objects which will inturn emit post_delete signal on B model. So on the second emit of post_delete the signal handler tries to delete an already deleted item which causes 'NoneType' object has no attribute 'delete'. You can use exception handler or just use the if condition to handle this.

def delete_parent(sender, instance, **kwargs):
    if instance.type_b:
        instance.type_b.delete()

post_delete.connect(delete_parent, sender=B)

Leave a comment