如何处理旧数据迁移中缺失的列?

How to deal with missing columns on old data migrations?

我想向 Django 模型添加一个新列。但是,我有一个过去的数据迁移创建了这个模型的对象,现在它不起作用,因为该列在迁移时不存在。

即我的模型是:

class MyModel(models.Model):
    name = models.CharField()
    foo = models.IntegerField()  # <-- I want to add this column

然而我的旧迁移是这样的:

def add_my_model(apps, schema_editor):
    MyModel.objects.create(name="blah")

class Migration(migrations.Migration):
    # ...
    operations = [
        migrations.RunPython(add_my_model),
    ]

当我尝试 运行 在新数据库上进行迁移时,此迁移失败并出现类似于以下的错误:

query = 'INSERT INTO "my_model" ("name", "foo") VALUES (?, ?)'
params = ['blah', None]

...

E       sqlite3.OperationalError: table my_model has no column named foo

处理这种情况的最佳方法是什么?

这在Django documentation中有解释:

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')

基本上而不是直接导入 MyModel 你应该做类似

def add_my_model(apps, schema_editor):
    MyModel = apps.get_model('yourappname', 'MyModel')
    MyModel.objects.create(name="blah")