Django - Associated OneToOne Record not being deleted

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)

Answers


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.


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.


Need Your Help

How To Deploy: Installing Mezzanine Theme

themes customization mezzanine pythonanywhere

How to install Mezzanine Theme exactly, step-by-step?

Adding table from another database to ASP.NET Dynamic Data + Entity Framework

asp.net entity-framework dynamic-data asp.net-dynamic-data

I have a table in another database I would like to scaffold via ASP.NET Dynamic Data and incorporate into my existing Entity Model - is there anyway to do this? (eg using a view or other mechanism or