2

Say I have these migrations:

  • 0001_initial
  • 0002_add_some_column
  • 0003_some_data_migration

All is fine at that point, but if I add one more schema migration:

  • 0004_add_bar_column

and then try to run the migrations against a new DB, or any DB that doesn't have 0003 yet, 0003 will bork out because "column bar does not exist".

What is the correct way to handle that scenario? Do data migrations always have to be re-done, when a schema migration is added, such that the data migrations always come last? Is there a way to make the data migration not care that "bar" doesn't exist yet? The data migration doesn't make use of "bar", but for some reason Django still thinks it needs it to exist at that point...

I'm using the build-in Django migrations, not South.

1 Answer 1

2

How are you accessing the models in the data migration?

Make sure you access the ORM through the apps / schema_editor rather than importing models directly.

The first argument passed to your migration worker function is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits.

i.e. in your data migration you should not have a line this:

from my_app import MyModel

but rather, something more like this

MyModel = apps.get_model("my_app", "MyModel")
Sign up to request clarification or add additional context in comments.

2 Comments

My app uses MyModel = apps.get_model('my_app', 'my_model) to grab the model, and then creates stuff via MyModel.objects.create(). Is that the correct way?
Actually, looks like there is one model that is being imported directly. That must be the issue. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.