[Django]-IntegrityError: FOREIGN KEY constraint failed in django

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:

  1. models.CASCADE: in that case it will remove all Returns related to the removed item;
  2. models.PROTECT: in that case it will raise an error to prevent removing the Issue; and
  3. models.SET_NULL: this is done on a NULLable field (so with null=Ture), in which case the impacted Return(s) will set the field to NULL/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.

๐Ÿ‘คdjvg

Leave a comment