[英]How to deal with missing columns on old data migrations?
I want to add a new column to a django model. However, I have a past data migration that creates an object of this model, which now doesn't work because the column didn't exist at the time of that migration.我想向 django model 添加一个新列。但是,我有一个过去的数据迁移,它创建了这个 model 的 object,现在它不起作用,因为该列在迁移时不存在。
ie my model is:即我的 model 是:
class MyModel(models.Model):
name = models.CharField()
foo = models.IntegerField() # <-- I want to add this column
however my old migration is this:但是我的旧迁移是这样的:
def add_my_model(apps, schema_editor):
MyModel.objects.create(name="blah")
class Migration(migrations.Migration):
# ...
operations = [
migrations.RunPython(add_my_model),
]
And when I try to run migrations on a fresh db, this migration fails with an error similar to this:当我尝试在新数据库上运行迁移时,此迁移失败并出现类似于以下的错误:
query = 'INSERT INTO "my_model" ("name", "foo") VALUES (?, ?)'
params = ['blah', None]
...
E sqlite3.OperationalError: table my_model has no column named foo
What's the best way to deal with this situation?处理这种情况的最佳方法是什么?
This is explained in Django documentation :这在Django 文档中有解释:
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')
basically instead of directly importing MyModel
you should be doing something like基本上而不是直接导入MyModel
你应该做类似的事情
def add_my_model(apps, schema_editor):
MyModel = apps.get_model('yourappname', 'MyModel')
MyModel.objects.create(name="blah")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.