In development, dropping and recreating database tables with db.drop_all() and db.create_all() wipes out all existing data. In production, destroying production data to add a new column or table is completely unacceptable.
Flask-Migrate wraps Alembic—SQLAlchemy's database migration engine—into the flask CLI, providing automated schema diffing and version-controlled migration scripts.
Install the extension:
In app.py:
Flask-Migrate adds the flask db command group to your terminal:
How data and code flow step-by-step
Run this once when starting a new project:
This creates a migrations/ directory in your project root containing Alembic configuration files and an alembic_version tracking table.
Whenever you add, modify, or delete columns or models in models.py, generate a revision:
Alembic inspects your SQLAlchemy models, compares them to the active database schema, and writes a Python migration script into migrations/versions/.
Always inspect the generated file in migrations/versions/. Notice the upgrade() and downgrade() functions:
Apply the revision to your database:
If a migration causes an issue, roll back to the previous revision:
render_as_batch=True in Migrate(app, db, render_as_batch=True) so Alembic recreates the table under the hood during complex migrations on SQLite.migrations/ directory must be checked into version control so team members and CI/CD deployment pipelines apply identical schema migrations.migrations/ directory be committed to Git?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| CRUD Operations, Query Filtering & Pagination | Password Hashing with Werkzeug Security |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.