#24163: Migrations fail when changing from OneToOneField to ForeignKey
----------------------------+--------------------------------------------
     Reporter:  harnash     |      Owner:  nobody
         Type:  Bug         |     Status:  new
    Component:  Migrations  |    Version:  1.7
     Severity:  Normal      |   Keywords:  OneToOneField ForeignKey MySQL
 Triage Stage:  Unreviewed  |  Has patch:  0
Easy pickings:  0           |      UI/UX:  0
----------------------------+--------------------------------------------
 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

--
Ticket URL: <https://code.djangoproject.com/ticket/24163>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/050.d73e449e3b717745ea22d1decbcebfe8%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to