Dealing with migrations on a team

When working on a project, branching for features is very common. However features often require changes to the database (new fields, updated fields or new models), this is where state changes gets introduced and it becomes tricky to switch or merge branches. Below is my goto advice for dealing with this situation.

First ensure that the feature branch is up to date before merging. This can be enforced in Github and Gitlab. Then it's a set of steps to follow before doing your final merge of a branch.

  1. Pull in the latest changes from the main branch, if your migrations are the latest then you are good to merge.
  2. However if there are conflicting migrations, then rollback your migrations and delete or move your migrations files. The move should only be in the case if data migrations are present.
  3. Run migrate on the existing migrations.
  4. Then run makemigrations to generate new migrations for your changes or copy your existing migrations back into the project and rename appropriately and update the migration dependencies
  5. Run migrate again to check everything still works as before and you're done.

The above should result in a linear migration history and at this point I will give a shout out to Adam Johnson's package django-linear-migrations which by the looks of it provides some excellent tooling to enforce a linear migration history.

Other strategies that will help is to leverage multiple apps as a team is then less likely that two people will be working on the same app at the same time which would mean Django's migration dependencies kick in to help keep the history in order