How can I delete all child objects of a parent object without deleting parent object with Django

Viewed 550

I have two models that use the same class as foreign key.

I don't want to delete the parent model (which is being used as foreign key) but delete the child models that are associated with the parent model.

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE, default=None)

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE, default=None)

Now I am deleting them separately as below :

b_list = B.objects.filter(a = A)
    for b_list_item in b_list:
        b_list_item.delete()

c_list = C.objects.filter(a = A)
    for c_list_item in c_list:
        c_list_item.delete()

How can I delete them all together with a single command ?

1 Answers

I would prefer this bulk delete option instead of iterating over the objects.

B.objects.filter(a=A).delete()
C.objects.filter(a=A).delete()
Related