Flask-Migrate Database Migration Examples

Learn practical examples of using Flask-Migrate for efficient database migrations in your Flask applications.
By Jamie

Introduction to Flask-Migrate

Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. It simplifies the process of managing changes to your database schema over time, enabling you to apply migrations consistently and efficiently. In this article, we present three practical examples of using Flask-Migrate for database migrations.

Example 1: Initial Database Migration

Context: You are starting a new Flask application and need to set up your initial database schema.

To begin, you’ll want to create your database models and then generate your initial migration script with Flask-Migrate. This ensures your database matches the models you’ve defined.

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

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

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

with app.app_context():
    db.create_all()

# Generate the migration script
!flask db init
!flask db migrate -m "Initial migration"
!flask db upgrade

Notes:

  • Ensure you have Flask-Migrate installed in your environment.
  • The db init command initializes a migrations directory. The db migrate command creates a new migration script, and db upgrade applies the migration to the database.

Example 2: Adding a New Column to an Existing Table

Context: You need to modify your existing User model to include a new column for user profiles.

When you want to add new attributes to your database model, you need to create another migration to reflect these changes in your database.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    bio = db.Column(db.String(250), nullable=True)  # New column for user bio

# After modifying the User model, run the following commands:
!flask db migrate -m "Add bio column to User"
!flask db upgrade

Notes:

  • Always ensure your application context is active when running migration commands.
  • You can check the migration history with flask db history.

Example 3: Renaming a Column in a Table

Context: You realize that the bio column in the User model should be renamed to profile_description for clarity.

Renaming columns is a common scenario in database migrations, and Flask-Migrate makes it straightforward to handle such changes.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    profile_description = db.Column(db.String(250), nullable=True)  # Renamed column

# After modifying the User model, run the following commands:
!flask db migrate -m "Rename bio to profile_description"
!flask db upgrade

Notes:

  • Ensure to update any references in your codebase that may still refer to the old column name.
  • You can customize migration scripts if you need to perform additional operations during the migration.

By following these examples of using Flask-Migrate for database migrations, you can effectively manage and evolve your database schema alongside your application development.