Delete cascade fails for nullable field
|Reported by:||amichair||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.3|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
In an app with models A, B and C, with foreign key fields from B to A and from C to B, the fields are defined with the default on_delete CASCADE, and the field of C (pointing to B) may be null; if A is deleted, B is deleted as well, but a C pointing to the deleted B is not deleted as expected - instead, a constraint violation exception is raised.
I traced this back to django/db/models/deletion.py, in the definition of Collector.add (line 103 in django 1.3). There is a comment explaining why dependencies do not need to be processed for nullable fields, however this is exactly what causes the bug - the dependency order is wrong and so the constraint is violated. If the 'and not nullable' condition is removed, it seems to work ok. Perhaps the code fails to consider the possibility that a field can be both nullable and with cascading deletes, for different purposes (i.e. a field is optional, but if it is set, must be a proper delete-cascading foreign key). Also the bug might be with whomever passes the nullable parameter to this method (i.e. CASCADE) - I don't know enough about the django design to tell.
The expected behavior would be for all foreign keys defined with on_delete CASCADE (the default behavior) to have the models deleted in a cascading manner, regardless of whether the fields are defined as being nullable or not.