Django-将ForeignKey关系更改为OneToOne [英] Django - Change a ForeignKey relation to OneToOne
问题描述
我在我的Django应用中使用South.我有两个模型正在从具有ForeignKey
关系更改为具有OneToOneField
关系.当我在开发数据库上运行此迁移时,它运行良好.当迁移作为创建测试数据库的一部分而运行时,最新的迁移失败,并显示MySQL 1005错误:无法创建表mydb.#sql-3249_1d(errno:121)".进行一些谷歌搜索显示,尝试添加与现有约束同名的约束通常是一个问题.迁移失败的具体行是:
I am using South with my Django app. I have two models that I am changing from having a ForeignKey
relation to having a OneToOneField
relation. When I ran this migration on my dev database, it ran fine. When the migrations get ran as part of creating a test database, the latest migration fails with a MySQL 1005 error: "Can't create table mydb.#sql-3249_1d (errno: 121)". Doing some Googling revealed that this is usually a problem with trying to add a constraint with the same name as an existing constraint. The specific line in the migration that it fails on is:
关系从以下位置更改:
class MyModel(models.Model):
othermodel = models.ForeignKey(OtherModel)
到
class MyModel(models.Model):
othermodel = models.OneToOneField(OtherModel)
在迁移过程中生成了以下语句:
which generated the following statements in the migration:
db.alter_column('myapp_mymodel', 'othermodel_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['myapp.OtherModel'], unique=True))
db.create_unique('myapp_mymodel', ['othermodel_id'])
但不是在create_unique
调用上失败,而是在alter_column
调用上失败.我运行以下命令来查看正在生成的SQL:
But instead of failing on the create_unique
call, it is failing on the alter_column
call. I ran the following command to see what SQL was being generated:
python manage.py migrate myapp 0010 --db-dry-run --verbosity=2
并打印出
myapp:0010_auto__chg_field_mymodel_othermodel__add_unique_mymodel
= ALTER TABLE `myapp_mymodel` ADD CONSTRAINT `myapp_mymodel_othermodel_id_uniq` UNIQUE (`othermodel_id`) []
= SET FOREIGN_KEY_CHECKS=1; []
= ALTER TABLE `myapp_mymodel` ADD CONSTRAINT `myapp_mymodel_othermodel_id_uniq` UNIQUE (`othermodel_id`) []
它试图两次运行ADD CONSTRAINT
似乎很奇怪,但是如果删除db.create_unique
调用,用--db-dry-run
运行它时不会生成SQL,但是如果运行,我仍然会收到错误消息它是真实的.
It seems strange that it is trying to run the ADD CONSTRAINT
twice, but if I remove the db.create_unique
call, no SQL is generated when I run it with --db-dry-run
, but I still get the error if I run it for real.
我在这里很茫然,不胜感激.
I am at a loss here, any help is appreciated.
推荐答案
您实际上根本不需要迁移.在挂钩下,OneToOne和ForeignKey关系具有兼容的数据库模式:一个简单的列,其中一个表中有另一个对象ID.
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.
如果您不想让告诉南方忽略此更改的麻烦,只需使用migrate --fake
伪造迁移内容即可.
Just fake the migration with migrate --fake
if you don't want to enter in the trouble of telling south to ignore this change.
这篇关于Django-将ForeignKey关系更改为OneToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!