Reputation: 47144
I have these models. The problem is that when I delete a dog record using Django Admin the associated collar record is not being deleted.
I'm on Django 1.2. I thought cascade delete was the default. It it an issue with Collar being linked to a legacy table?
Much thanks in advance.
class Collar(models.Model):
serial_number = models.AutoField(primary_key=True, db_column='serial_number')
weight = models.CharField(max_length=10)
class Meta:
db_table = u'existing_table_from_before_django_was_born'
class Dog(models.Model):
size = models.CharField(max_length=10)
collar = models.OneToOneField(Collar,blank=True, null=True, editable=False)
Upvotes: 0
Views: 437
Reputation: 239400
You have to think about the relationships and why the delete cascade exists. The FK is on Dog
(the field is in its table in the DB). If you delete Dog
, it just deletes Dog
. There's no need to delete anything else. However, if you delete Collar
, then you may end up with an issue with referential integrity if the the Dog
that associates with it is not also deleted. In your case here, the field is NULL-able, so you could simply set the collar field to NULL and fix the referential integrity problem, but in other scenarios, the Dog
would have to be deleted to maintain database integrity.
The delete cascade often ends up being very handy, but it's important to remember that the goal of it is not to make your life simpler, but rather to preserve database integrity. As a result, there's no motivation to clean up the opposite end of the relationship (deleting Collar
when you delete Dog
) because no problems will result from that.
Upvotes: 2
Reputation: 1950
It is not an issue of the connection to a legacy table. The cascade deletion will work of you delete the Collar object, then the related Dog object will be deleted (probably if you remove blank=True, null=True).
To delete Collar after deletion of Dog you need to overload the delete method of Dog.
Upvotes: 2