All posts

Fix Migration Error in Python

Resolve Alembic and Django migration errors in Python, covering dependency conflicts, merge migrations, and autogenerate issues.

Python Migration Errors

Python's two main migration tools — Alembic (SQLAlchemy) and Django's built-in migrations — each have common failure patterns.

Alembic: Multiple Heads

When branches create migrations independently:

alembic heads
# Shows multiple heads

# Create a merge migration
alembic merge -m "merge branches" head1 head2
alembic upgrade head

Alembic: Autogenerate Misses Changes

Autogenerate doesn't detect everything. Check the generated file:

alembic revision --autogenerate -m "add user email"
# Always review the generated migration!

Common misses: column type changes, constraint names, server defaults. Add them manually:

def upgrade():
    op.add_column('users', sa.Column('email', sa.String(255)))
    op.create_index('ix_users_email', 'users', ['email'])

def downgrade():
    op.drop_index('ix_users_email', 'users')
    op.drop_column('users', 'email')

Django: Conflicting Migrations

python manage.py makemigrations --merge

Django: Fake Migration

If the database already has the changes:

python manage.py migrate myapp 0005 --fake

Circular Dependencies

# Django — use string references
class Post(models.Model):
    author = models.ForeignKey('users.User', on_delete=models.CASCADE)

Alembic: Offline Mode for Review

# Generate SQL without running it
alembic upgrade head --sql > migration.sql
# Review, then apply manually

Bugsly captures migration errors during application startup, including the specific migration that failed and the database error message.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free