I have a model:
class Project(Model):
name = models.TextField(...)
... bunch of fields ...
I also have some models that track history in my application. These models have ForeignKey references to the Project model:
class Historical_Milestone(Model):
project = models.ForeignKey('Project', db_index=True, related_name='+',
on_delete=models.DO_NOTHING, blank=True, null=True)
When I delete an item in my Project table, I get the following IntegrityError:
update or delete on table "project" violates foreign key constraint {...} on table "historical_milestone" DETAIL: Key (id)=(123) is still referenced from table "historical_milestone".
The column in the historical table has related_name='+' set (indicating that I don't want the reverse lookup), and I have the on_delete=models.DO_NOTHING parameter set. According to the documentation on the DO_NOTHING option:
If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.
Shouldn't the related_name flag indicating I don't care about the reverse relationship take care of this? What manual step do I need to take to modify the Historical_Milestone table to prevent this error from happening?
The related_name is for convenience, it doesn't affect the foreign key constraints that Django creates. Setting related_name='+' simply means you don't want to be able to access product.historical_milestone_set (or similar) in the ORM.
If you want to keep the id after the project is deleted, and not enforce a foreign key constraint, it might be better to use an integer field.
class Historical_Milestone(Model):
project_id = models.PositiveIntegerField(db_index=True, blank=True, null=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With