我想向 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
處理這種情況的最佳方法是什么?
uj5u.com熱心網友回復:
這在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')
基本上而不是直接匯入MyModel你應該做類似的事情
def add_my_model(apps, schema_editor):
MyModel = apps.get_model('yourappname', 'MyModel')
MyModel.objects.create(name="blah")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440196.html
