Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django migration fails on change of to_field

In my Django model I had a field like this one (simplified):

category = models.ForeignKey(EnumValue, to_field='code', related_name='+', verbose_name="Kategorie", db_column='Kategorie')

Then I removed the to_field argument to convert the foreign key back to one that points to the primary key.

Django migration produced just a simple AlterField for this change and seems not to modify the foreign key or translate existing data correctly. Anyways, I get this error message, when applying the migration:

pymysql.err.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails

I cannot find anything about this specific case in the web. I would say this is a Django migration bug. Do you agree? Do you know a workaround for this?

like image 895
Kit Fisto Avatar asked Oct 12 '25 13:10

Kit Fisto


1 Answers

The following worked for me:

  1. Add a second field that points to the primary key of the referenced class.
  2. In the migration file add a python routine that transfers the references from the existing field to the new field.
  3. In a second migration delete the old field and rename the new one.
like image 132
Kit Fisto Avatar answered Oct 14 '25 03:10

Kit Fisto