albin antony
albin antony

Reputation: 179

Delete parent object when child object is deleted in Django

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

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

In a one-to-many relationship in Django, how do I delete the "one" object (model 'A') when I delete one of the related "many" objects (model 'B')? I'm deleting the model 'B' object through the Django admin bulk delete option.

Upvotes: 3

Views: 2790

Answers (3)

Sagar Ramachandrappa
Sagar Ramachandrappa

Reputation: 1461

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)

Upvotes: 0

Lemayzeur
Lemayzeur

Reputation: 8525

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)

Upvotes: 2

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

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

Upvotes: 3

Related Questions