﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
24528	Migration fails because of duplicate constraint name when renaming and re-creating a model	Remiremi	nobody	"I have reached a point where django migration fails because it tries to create a constraint with a name that is already used by another constraint. I am using MySQL and tried with both PyMySQL connector and Oracle's mysql-connector-python. I might be wrong but I suspect the same would happen with other connectors or with PostgreSQL. I have tried with Django 1.7.6 and 1.7.7.

1. Create model ModelB with a FK on ModelA

{{{
class ModelA(models.Model):
        pass

class ModelB(models.Model):
        a = models.ForeignKey(ModelA)
}}}

2. Run manage.py makemigrations.

3. Rename ModelB to ModelC

{{{
class ModelA(models.Model):
        pass

class ModelC(models.Model):
        a = models.ForeignKey(ModelA)
}}}

4. Run manage.py makemigrations. When asked whether you renamed ModelB to ModelC, answer yes.

5. Add back Model B

{{{
class ModelA(models.Model):
        pass

class ModelC(models.Model):
        a = models.ForeignKey(ModelA)

class ModelB(models.Model):
        a = models.ForeignKey(ModelA)
}}}

6. Run manage.py makemigrations

7. Run manage.py migrate

This last step fails with error
{{{
django.db.utils.InternalError: (1022, u""Can't write; duplicate key in table '#sql-37bd_127'"")
}}}

The django.db log shows that the SQL query causing the failure is:

{{{
[24/Mar/2015 11:11:46] DEBUG [django.db.backends.schema:94] ALTER TABLE `myapp_modelb` ADD CONSTRAINT `myapp_modelb_a_id_73cac46a7c85ae49_fk_myapp_modela_id` FOREIGN KEY (`modela_id`) REFERENCES `myapp_modela` (`id`); (params [])
}}}

After inspection of the database, ModelC does have a constraint with that name.

It's probably possible to go around this issue by renaming ModelC'S constraint, but '''the same failure also happens when building the test database''' by running manage.py test. I do not have a workaround for that case.

Full output of the migration is attached."	Bug	closed	Migrations	1.7	Normal	duplicate			Accepted	0	0	0	0	0	0
