﻿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
24163	Migrations fail when changing from OneToOneField to ForeignKey	Łukasz Harasimowicz	Markus Holtermann	"Hi!

My team and I have encountered a problem in migrations when changing relationship between models from OneToOneField to ForeignKey. 

Original thread on django-users can be found here: 
https://groups.google.com/forum/?#!topic/django-users/-NUbqzS4jQs

== Environment ==
* OS: Unix (Ubuntu 14.04)/OSX
* Django: 1.7.3
* DB: MySQL 5.6.22

== Steps to reproduce ==

1. Create two models:

{{{
class Model_A(models.Model):
    id_A = models.AutoField(primary_key=True)


class Model_B(models.Model):
    model_a = models.OneToOneField(Model_A)
}}}

2. Make migrations and perform migration. So far everything is OK. 

3. Now change OneToOneField to ForeignKey:

{{{
class Model_A(models.Model):
    id_A = models.AutoField(primary_key=True)


class Model_B(models.Model):
    model_a = models.ForeignKey(Model_A)
}}}

4. Run migrations (makemigrations) and apply changes to db (migrate). We get this error:

we get an error:

{{{
Cannot drop index 'model_a_id': needed in a foreign key constraint
}}}

It seems that Django tries to run SQL commands in following order:

{{{
ALTER TABLE 'xxx' DROP INDEX 'yyy' and
ALTER TABLE `xxx` DROP FOREIGN KEY `xxx_yyy_id_{some_hash}_fk_yyy_id`;
}}}

but if above commands are run in reverse order:

{{{
ALTER TABLE `xxx` DROP FOREIGN KEY `xxx_yyy_id_{some_hash}_fk_yyy_id`;
ALTER TABLE 'xxx' DROP INDEX 'yyy' and
}}}

everything is OK.

I have created sample project where it can be reproduced (last three commits are reproducing above steps): https://github.com/harnash/django-migration-bug/commits/master"	Bug	closed	Migrations	1.7	Normal	fixed	OneToOneField ForeignKey MySQL	Markus Holtermann	Ready for checkin	1	0	0	0	0	0
