如何将 IntegerField 迁移到外键

时间:2021-04-26 13:06:08

标签: mysql django django-models django-migrations

我有一个要迁移到 Django 的旧数据库。

我有这样的模型:

class MyModel(models.Model):
    other_id = models.IntegerField()

这是一个填充了有效数据的现有表格。我想迁移到

class MyModel(models.Model):
    newbie = models.ForeignKey(
        OtherModel,
        on_delete=models.CASCADE,
        db_constraint=False,
        db_column="other_id",
    )

然而,生成的迁移一直坚持添加已经存在的字段而不是删除它:

python manage.py sqlmigrate app 0069

BEGIN;
--
-- Add field
--
ALTER TABLE `mymodel` ADD COLUMN `other_id` integer DEFAULT 1 NOT NULL;
ALTER TABLE `mymodel` ALTER COLUMN `other_id` DROP DEFAULT;
--
-- Remove field
--
ALTER TABLE `mymodel` DROP COLUMN `other_id`;

有没有办法说服 Django 在没有这个练习的情况下将该字段视为外键?我想避免--fake迁移的需要。

1 个答案:

答案 0 :(得分:1)

根据建议,编写自己的迁移会有所帮助:

operations = [
    migrations.AlterField(
        model_name="mymodel",
        name="other_id",
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.CASCADE,
            related_name="other",
            to="ddcz.UserProfile",
            db_column="other_id",
            db_constraint=False,
        ),
    ),
    migrations.RenameField("MyModel", "other_id", "other"),
]
相关问题