1

I have an object model as follows:

class Corporation(models.Model):
    corp_id = models.AutoField(primary_key=True)
    original_name = models.CharField(max_length=1000, blank=True, null=True)
    address = models.ManyToManyField(Address, related_name='corp_address')

class Person(models.Model):
    person_id = models.AutoField(primary_key=True)
    person_address = models.ManyToManyField(Address, related_name='person_address')

class Address(models.Model):
    address1 = models.CharField(max_length=500, blank=True, null=True)
    address2 = models.CharField(max_length=500, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)
    state = models.CharField(max_length=100, blank=True, null=True)
    zipcode = models.CharField(max_length=20, blank=True, null=True)
    country = models.CharField(max_length=100, blank=True, null=True)

class Committee(Corporation):
    name = models.CharField(blank=True, max_length=200, null=True)
    industry = models.CharField(blank=True, max_length=100, null=True)

When I create a Committee object, I create a Corporation and an Address object. A single Address object may have multiple Corporations pointing to it.

However, when I do Committee.objects.delete(), Django deletes the Committee object but not the related Corporation or Address object.

When I delete a Committee object, I want to delete the associated Address object if another object does not point to it. I also want to delete the associated Corporation object if another object does not point to it.

How can I do this conditional cascaded delete?

book
  • 253
  • 1
  • 2
  • 10

1 Answers1

3

Check out on_delete set to cascade in django which will delete the associated records also .

In your models please add on_delete = models.CASCADE in this fashion:

 class Car(models.Model):
     manufacturer = models.ForeignKey(
         'Manufacturer', on_delete=models.CASCADE)

Here is a good post which explains models.CASCADE delete and ManyToMany relation on Django.

Community
  • 1
  • 1
kt14
  • 838
  • 15
  • 25
  • Thank you. I notice that you use ForeignKey() vs ManytoMany() in your example. Will your example delete the Address object if multiple objects point to it? – book Aug 08 '16 at 16:28
  • I think you have to understand how ManyToMany relations and Cascade delete works. I have updated the answer with a post which gives you a better understanding. – kt14 Aug 08 '16 at 16:41