2๐
Do DO_NOTHING
is typically not a good option since (most) databases will check referential integrity. This means that they guarantee that if a ForeignKey
refers (in this case to an Issue
), then that means that the table that stores the issues should have a record with the primary key the Return
item refers to.
Often DO_NOTHING
is used in combination with a certain trigger in the database system (that Django is not aware of).
Typically the most popular choices foron_delete
are:
models.CASCADE
: in that case it will remove allReturn
s related to the removed item;models.PROTECT
: in that case it will raise an error to prevent removing theIssue
; andmodels.SET_NULL
: this is done on aNULL
able field (so withnull=Ture
), in which case the impactedReturn
(s) will set the field toNULL
/None
.
Another option might be to "soft delete" records, for example with the django-soft-delete
package [pypi]. In that case a boolean is added to the Issue
that specifies if the item is removed. The package will also transparently filter the objects, such that you only retrieve records that are "alive".
1๐
This edge case is not directly relevant for the OP, but may help others that wind up here based on the title:
An IntegrityError: FOREIGN KEY constraint failed
will also be raised when trying to delete
some object x
, if there is a table in your database that Django is unaware of, and this table has a reference to object x
.
This can happen, for example, if you remove a model from your code without properly migrating the changes.
As a result, the table remains in the database, but Django does not know anything about it, so, when object x
is deleted, Django does not know it should also delete the corresponding row from this "orphaned" table.