Django迁移抛出1072 - 表中不存在关键列'car_make_id'

时间:2016-02-02 16:19:59

标签: python mysql django django-migrations

这是简化的任务和设置(Django 1.8,MySQL,Python 2.7),我有:

class Car(models.Model):
    make = models.ForeignKey(CarMake)

class Bike(models.Model):
    make = models.ForeignKey(BikeMake)

class CarMake(models.Model):
    name = models.CharField(max_length=32)

class BikeMake(models.Model):
    name = models.CharField(max_length=32)

现在,我需要完全放弃 BikeMake 模型,以便使用 BikeMake 中的值更新 CarMake 模型,并更新外键自行车中的关系。

我创建了以下迁移,使用 BikeMake 中的名称更新 CarMake ,添加临时字段 Bike.car_make ,迁移数据从 Bike.make Bike.car_make ,删除 Bike.make 字段并将 Bike.car_make 重命名为 Bike.make

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations


def update_car_makes(apps, schema_editor):
    """Update CarMakes with BikeMakes"""
    BikeMake = apps.get_model('my_app', 'BikeMake')
    CarMake = apps.get_model('my_app', 'CarMake')

    for item in BikeMake.objects.all():
        if not CarMake.objects.filter(name=item.name).exists():
            CarMake.objects.create(name=item.name)


def remove_car_makers(apps, schema_editor):
    """Restore original CarMake (exclude BikeMake)"""
    pass


def migrate_to_car_make(apps, schema_editor):
    """Set Bike.car_make according to Bike.make"""
    CarMake = apps.get_model('my_app', 'CarMake')
    Bike = apps.get_model('my_app', 'Bike')
    for item in Bike.objects.all():
        old_make = item.make
        new_make = CarMake.objects.get(name=old_make.name)
        item.car_make = new_make
        item.save()


def reverse_migrate_to_car_make(apps, schema_editor):
    pass


def dummy_forwards(apps, schema_editor):
    # Empty forward migration needed for having custom backwards migration
    pass


def restore_make_column_data(apps, schema_editor):
    BikeMake = apps.get_model('products', 'BikeMake')
    Bike = apps.get_model('products', 'Bike')

    for item in Bike.objects.all():
        old_make = item.bike_make
        new_make = BikeMake.objects.get(name=old_make.name)
        item.make = new_make
        item.save()


class Migration(migrations.Migration):

    dependencies = [('my_app', '0001_blah_blah')]

    operations = [
        migrations.RunPython(
            update_car_makers,
            reverse_code=remove_car_makers
        ),
        migrations.AddField(
            model_name='bike',
            name='car_make',
            field=models.ForeignKey(default=1, to='my_app.CarMake'),
            preserve_default=False
        ),
        migrations.RunPython(
            migrate_to_car_make,
            reverse_code=reverse_migrate_to_car_make
        ),
        migrations.RunPython(
            dummy_forwards,
            reverse_code=restore_make_column_data
        ),
        migrations.RemoveField(
            model_name='bike',
            name='make',
        ),
        migrations.RenameField(
            model_name='bike',
            old_name='car_make',
            new_name='make'
        )
    ]

当我尝试运行它时,我在运行上一次操作时遇到#1072错误:migrations.RenameField。现在有趣的部分是来自DB POV的一切都是完整的,数据迁移,列重命名,只有迁移没有标记为已完成并且抛出了错误。

此外,如果我只是将migrations.RenameField移动到单独的迁移文件并连续运行两次迁移 - 一切正常,并且不会引发#1072错误。

此外,我尝试在migrations.RenameField之前插入一个断点,并且我确认 Bike.car_make 列已存在且我可以正常获取 Bike <的所有对象/ strong>那时的模型。

导致错误的MySQL查询如下:

CREATE INDEX `my_app_bike_c2036163` ON `my_app_bike` (`car_make_id`)

任何想法如何修复它并将其放在一个迁移文件中?提前谢谢!

更新04.02.16

正如@kvikshaug指出的那样,这是因为Django在执行所有操作后创建索引和约束,即当时生成用于创建索引和/或约束的原始SQL,执行相应的操作(在我的情况下{{1} }),但该查询实际上是在最后运行,因此是错误。

对于相对较小的模式,一种可能的解决方案可能是使用Django的RunSQL并自己键入原始查询,但这非常麻烦+您必须自己创建约束。

所以我选择了重命名迁移。

1 个答案:

答案 0 :(得分:1)

Django迁移在执行所有操作后创建索引。你的第二个操作,添加字段car_make,使Django添加你注意到的CREATE INDEX命令导致错误:

CREATE INDEX `my_app_bike_c2036163` ON `my_app_bike` (`car_make_id`)

即使您稍后重命名该字段,Django仍会尝试为现在缺少的car_make字段创建索引,这就是您收到错误的原因。您可以通过以下方式清楚地看到正在运行sqlmigrate

$ ./manage.py sqlmigrate my_app 0002_blah_blah
BEGIN;
--
-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:
-- Raw Python operation
--
--
-- Add field car_make to bike
--
ALTER TABLE "my_app_bike" ADD COLUMN "car_make_id" integer DEFAULT 1 NOT NULL;
ALTER TABLE "my_app_bike" ALTER COLUMN "car_make_id" DROP DEFAULT;
--
-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:
-- Raw Python operation
--
--
-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:
-- Raw Python operation
--
--
-- Remove field make from bike
--
ALTER TABLE "my_app_bike" DROP CONSTRAINT "my_app_bike_make_id_5615ed11_fk_my_app_bikemake_id";
ALTER TABLE "my_app_bike" DROP COLUMN "make_id" CASCADE;
--
-- Rename field car_make on bike to make
--
ALTER TABLE "my_app_bike" RENAME COLUMN "car_make_id" TO "make_id";
CREATE INDEX "my_app_bike_78e8ca60" ON "my_app_bike" ("car_make_id");
ALTER TABLE "my_app_bike" ADD CONSTRAINT "my_app_bike_car_make_id_6c42be09_fk_my_app_carmake_id" FOREIGN KEY ("car_make_id") REFERENCES "my_app_carmake" ("id") DEFERRABLE INITIALLY DEFERRED;

COMMIT;

您可以尝试将此报告为错误(或搜索;可能已经报告过),但您可能最好遵循Alasdairs的建议并将迁移分开。