Opened 6 years ago

Closed 6 years ago

#17579 closed Bug (worksforme)

Delete cascade fails for nullable field

Reported by: amichair Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: 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/, 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.

Change History (1)

comment:1 Changed 6 years ago by Tomek Paczkowski

Resolution: worksforme
Status: newclosed

I've tried to reproduce this using code in following gist: and both django 1.3.1 and todays trunk.

I did not see the error described. Maybe problem is more complicated? Closing as works for me.

Note: See TracTickets for help on using tickets.
Back to Top