[patch] Add support for a faux ON DELETE RESTRICT functionality
|Reported by:||Jeff Forcier||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:|
|Cc:||jeff@…, gabor@…||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||yes|
|Needs tests:||yes||Patch needs improvement:||yes|
I wanted a way to specify that records should not be deleted if they have other records associated with them, similar to SQL's 'ON DELETE RESTRICT'. Currently the only documented behavior for Django is closer to an in-code 'ON DELETE CASCADE'.
To make things a little more complex, I also wanted to quantify what's checked for in the 'RESTRICT'--specifically, sub-items of a record, such as an Address for a Contact, should NOT be part of the RESTRICT, but other, more complex relationships should be checked.
This patch adds a 'restrict_delete' keyword to the META classes of Model classes, which is a boolean that defaults to False (e.g. the normal CASCADE behavior). If this is set to True for a Model class, the following happens on a call to the .delete() method of that class's instances:
- A set consisting of all related fields is constructed, mirroring the calls used to find out what to delete.
- Any fields marked as 'follow' (this includes the implicit 'follow' set on things edited_inline) are taken out of this set - they are the 'sub-items' mentioned above.
- Calls to get_count for the remaining related fields are made, and if any are non-zero, an AssertionError is raised and the deletion does not occur.
This is primarily to scratch a personal itch for a project, but I assume others may want the functionality, and I certainly think that the core devs would want to review delete()'s current behavior at some point as it's quite inflexible. I've seen one unanswered question on django-users asking for something like this, for example :)
Change History (23)
comment:9 Changed 10 years ago by
|Patch needs improvement:||set|
|Triage Stage:||Unreviewed → Accepted|