0
0
FlaskHow-ToBeginner · 4 min read

How to Use Flask-Migrate for Database Migrations

Use flask-migrate by initializing it with your Flask app and SQLAlchemy database, then run commands like flask db init, flask db migrate, and flask db upgrade to manage database schema changes smoothly. It automates migration scripts and applies them to your database.
📐

Syntax

Flask-Migrate uses command line commands to manage migrations. The main commands are:

  • flask db init: Creates a migrations folder to track changes.
  • flask db migrate -m "message": Generates migration scripts based on model changes.
  • flask db upgrade: Applies migrations to the database.
  • flask db downgrade: Reverts the last migration.

You first set up Flask-Migrate by linking it to your Flask app and SQLAlchemy database.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
💻

Example

This example shows a simple Flask app with a User model. It demonstrates initializing Flask-Migrate, creating migration scripts, and applying them.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)

if __name__ == '__main__':
    app.run()
Output
Running the commands: $ flask db init $ flask db migrate -m "Create user table" $ flask db upgrade Creates the migrations folder, generates migration scripts, and updates the database with the User table.
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting SQLALCHEMY_DATABASE_URI correctly, causing connection errors.
  • Forgetting to run flask db migrate after model changes, so migrations are not generated.
  • Running flask db upgrade without migrations, causing errors.
  • Not importing models before migration commands, so changes are not detected.

Always ensure your app and models are imported in the migration context.

python
## Wrong: Forgetting to import models
# migrations detect no changes

## Right: Import models in manage.py or app entry point
from yourapp import models
📊

Quick Reference

CommandDescription
flask db initCreate migrations folder to track changes
flask db migrate -m "message"Generate migration scripts from model changes
flask db upgradeApply migrations to the database
flask db downgradeRevert the last migration
flask db historyShow migration history
flask db currentShow current migration applied

Key Takeaways

Initialize Flask-Migrate with your Flask app and SQLAlchemy database before running migration commands.
Use 'flask db migrate' to generate migration scripts after changing models.
Apply migrations to the database with 'flask db upgrade'.
Always import your models before running migration commands to detect changes.
Check migration status with 'flask db current' and 'flask db history'.