Django - Migration is applied before its dependency

I'm working on a Django project, and had some trouble which a coworker helped me overcome. However, when we were investigating the issue, she deleted a migration because it seemed to cause some issues. At the end, the issue wasn't related to that, but she left the company now.

The project seemed fine, until I tried to apply a change to a model and run "makemigrations" and "migrate", and saw some errors, stating that Migration <migration_name> is applied before its dependency <migration2> on database 'default'.

For what I saw online and my coworker told me, I decided to delete the local database and the migrations and re-do them. But when I tried to make the migrations from scratch, some errors appeared, and I tried to recover the migrations in our production server and copy them to my local project, to maybe migrate those instead of generating them on my local project.

However, I still can't run the project properly, even with the "good" migrations I got from the production server, it still says that a migration is applied before its dependency. I tried migrating each migration individually, with

python manage.py migrate project_name migration_name

But it says the same exact error, so I don't know if my syntax is incorrect or what am I not understanding. What would you recommend me do, or what could be wrong with what I've done? I'm relatively new to Django, so I don't know where to look anymore.

Upvotes: 1

Views: 4589

Answers (2)

tbrlpld
tbrlpld

Reputation: 877

I have been running into this while my migrations do have a seemingly logical order.

In my case, this was caused by the database and the code where out of sync. This often happens when working with multiple environment branches (e.g. one for production and another for development/staging/testing).

To solve the issue and being able to e.g. create merge migrations I had to reset my local database to completely empty state (of course after creating a backup).

Btw. ./manage.py flush does not work! That only empties the database but keeps the schema. I had to fully delete the database and recreate it. E.g. for Postgres dropdb <dbname> and createdb <dbname>

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Migrations must indeed be applied in the correct order, and this order is indicated by the dependencies attribute of the Migration class in your migrations files.

Sometimes, for various reasons (most often because of two migrations being created in two distinct branches), this attribute's value ends up being wrong. The proper solution is, simply, to check the migration files indicated in the error message (and possibly some of the migrations in between etc) and manually correct the dependencies on each so you're back to a coherent order.

Upvotes: 5

Related Questions