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.
i.e. my model is:
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?
CodePudding user response:
This is explained in 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')
basically instead of directly importing MyModel
you should be doing something like
def add_my_model(apps, schema_editor):
MyModel = apps.get_model('yourappname', 'MyModel')
MyModel.objects.create(name="blah")