Reputation: 253
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?
Upvotes: 1
Views: 2511
Reputation: 846
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.
Upvotes: 3