如何将 IntegerField 迁移到 ForeignKey

How To Migrate IntegerField To ForeignKey

我有一个遗留数据库,我正在迁移到 Django。

我有这样的模型:

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

这是现有的 table,其中填充了有效数据。我想迁移到

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 将该字段视为 ForeignKey?我想避免 --fake 迁移的需要。

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

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"),
]