0
0
DjangoDebug / FixBeginner · 3 min read

How to Fix Migration Error in Django: Simple Steps

To fix a migration error in Django, first identify the cause by reading the error message, then correct your model or migration files accordingly. Run python manage.py makemigrations and python manage.py migrate again to apply the fix.
🔍

Why This Happens

Django migration errors often happen when your database schema and your models get out of sync. This can occur if you change a model field but forget to create or apply migrations, or if migrations conflict or are missing.

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    published_date = models.DateField()

# Later you rename 'published_date' to 'publish_date' in the model but forget to create a migration.
Output
django.db.utils.OperationalError: no such column: app_book.publish_date
🔧

The Fix

Update your models correctly and then create new migrations with python manage.py makemigrations. After that, apply migrations with python manage.py migrate. This syncs your database with your models.

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    publish_date = models.DateField()

# Then run in terminal:
# python manage.py makemigrations
# python manage.py migrate
Output
Migrations for 'app': app/migrations/0002_auto.py - Rename field published_date to publish_date on book Operations to perform: Apply all migrations: app Running migrations: Applying app.0002_auto... OK
🛡️

Prevention

Always create and apply migrations immediately after changing models. Use version control to track migration files. Avoid manually editing migration files unless necessary. Run python manage.py showmigrations to check migration status.

⚠️

Related Errors

Common related errors include:

  • Conflicting migrations: Happens when two migrations modify the same model differently. Fix by merging migrations.
  • Missing migrations: Occurs if you forget to run makemigrations. Fix by running it.
  • Database locked: Happens if another process uses the database. Fix by closing other connections.

Key Takeaways

Always run makemigrations and migrate after changing models to avoid errors.
Read error messages carefully to identify the migration problem.
Use version control to track migration files and avoid conflicts.
Avoid manual edits to migration files unless you understand the impact.
Check migration status with showmigrations to ensure all are applied.