Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 612
albin antony Avatar asked Feb 03 '26 22:02

albin antony


2 Answers

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
like image 166
Davit Tovmasyan Avatar answered Feb 05 '26 13:02

Davit Tovmasyan


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)
like image 25
Lemayzeur Avatar answered Feb 05 '26 11:02

Lemayzeur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!