Code

Opened 2 years ago

Closed 2 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

Description

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.

Attachments (0)

Change History (1)

comment:1 Changed 2 years ago by oinopion

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

I've tried to reproduce this using code in following gist: https://gist.github.com/1745211 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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.