How to Fix Migration Conflicts in Django Quickly
python manage.py makemigrations --merge to combine conflicting migrations, then test and apply them with python manage.py migrate.Why This Happens
Migration conflicts occur when multiple developers create migrations for the same Django app independently. Each migration file has a unique name and a reference to the previous migration. If two migrations are created from the same starting point but don't know about each other, Django cannot decide which to apply first.
This usually happens when branches are merged without syncing migrations first.
# Example of conflicting migrations in the same app # migration_0002_add_field.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='mymodel', name='field_a', field=models.CharField(max_length=100), ), ] # migration_0003_add_field.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='mymodel', name='field_b', field=models.IntegerField(default=0), ), ]
The Fix
To fix migration conflicts, run python manage.py makemigrations --merge. This command creates a new migration that combines the conflicting ones by setting both as dependencies. After merging, run python manage.py migrate to apply the combined migrations.
This keeps your database schema consistent and avoids errors.
# Run this command in your terminal
python manage.py makemigrations --merge
# Then apply migrations
python manage.py migratePrevention
To avoid migration conflicts in the future:
- Communicate with your team to coordinate migration creation.
- Pull the latest migrations before creating new ones.
- Use feature branches and merge migrations regularly.
- Review migration files during code reviews.
These habits keep migrations linear and reduce conflicts.
Related Errors
Other migration-related errors include:
- Missing migrations: Happens when model changes are not followed by migration creation. Fix by running
makemigrations. - Applied but missing migrations: Occurs if migration files are deleted after applying. Fix by restoring migrations or faking migrations.
- Database schema mismatch: Happens if migrations are not applied in order. Fix by running
migratecarefully.