Django - Change a ForeignKey relation to OneToOne

◇◆丶佛笑我妖孽 提交于 2019-12-03 05:03:06

You actually don't need a migration at all. OneToOne and ForeignKey relations have a compatible database schema under the hook: a simple column witht the other object ID in one of the table.

Just fake the migration with migrate --fake if you don't want to enter in the trouble of telling south to ignore this change.

I agree with @e-satis that the goal here is to fake a migration, but I suggest a different approach if you're working with a team.

If you create a migration then --fake it, all your team members will need to remember to --fake it as well. If any of them don't do this when they upgrade, you're in trouble.

A better approach is to create an empty migration, then migrate it:

manage.py schemamigration yourapp --empty fake_migration_of_foreign_key_to_onetoone
manage.py migrate  # Like you always do! 

First thing I would try would be to add a db.delete_unique(...) in various places to see if I could hack it.

Failing that, I'd split it up into 3 migrations:

  1. a schema migration to add a new column for the OneToOne
  2. a data migration to copy all FK values from old column over to new
  3. a schema migration to remove the old column, which then I'd edit manually to include a command to rename the new column to the same as the old one.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!