Bird
Raised Fist0
Flaskframework~10 mins

Database migrations with Flask-Migrate - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Database migrations with Flask-Migrate
Write/Change Models
↓
Run 'flask db migrate'
↓
Generate Migration Script
↓
Review/Edit Script
↓
Run 'flask db upgrade'
↓
Apply Changes to DB
↓
Database Updated
You first change your data models, then create a migration script, and finally apply it to update the database.
Execution Sample
Flask
from flask_migrate import Migrate
migrate = Migrate(app, db)

# Terminal commands:
# flask db migrate -m "Add user email"
# flask db upgrade
This sets up Flask-Migrate and runs commands to create and apply a migration.
Execution Table
StepActionCommand/CodeResult
1Change model codeAdd 'email' field to User modelModel updated in code
2Generate migrationflask db migrate -m "Add user email"Migration script created in migrations/versions
3Review migrationCheck generated script for correctnessMigration script ready
4Apply migrationflask db upgradeDatabase schema updated with new 'email' column
5VerifyCheck DB schema or app behaviorNew column available in DB
💡
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
User model fieldsid, usernameid, username, emailMigration script includes 'email' columnDatabase schema includes 'email' columnDatabase schema includes 'email' column
Key Moments - 2 Insights
Why do I need to run 'flask db migrate' after changing my models?
Because 'flask db migrate' creates a migration script that tells the database how to update its structure to match your new model changes, as shown in step 2 of the execution table.
What happens if I skip 'flask db upgrade'?
Skipping 'flask db upgrade' means the database won't apply the changes from the migration script, so your database schema stays old and mismatched with your models, as seen between steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result after running 'flask db migrate'?
ADatabase schema updated
BMigration script created in migrations/versions
CModel code changed
DMigration script applied to DB
💡 Hint
Check step 2 in the execution table for the result of 'flask db migrate'
At which step does the database schema actually get updated?
AStep 2
BStep 1
CStep 4
DStep 3
💡 Hint
Look for when 'flask db upgrade' is run in the execution table
If you forget to add the new field to your model before migrating, what happens?
AMigration script will not include the new field
BDatabase will update correctly anyway
CMigration script will fail to generate
DDatabase schema will update with extra fields
💡 Hint
Refer to the variable tracker and step 1 where model changes happen before migration
Concept Snapshot
Flask-Migrate helps update your database schema when models change.
1. Change your models in code.
2. Run 'flask db migrate' to create migration scripts.
3. Review scripts if needed.
4. Run 'flask db upgrade' to apply changes to the database.
Always migrate before upgrading to keep DB and models in sync.
Full Transcript
Database migrations with Flask-Migrate involve changing your data models first, then generating a migration script using 'flask db migrate'. This script describes how to update the database schema. After reviewing the script, you apply the changes with 'flask db upgrade', which updates the actual database. This process keeps your database structure in sync with your application models. Skipping migration or upgrade steps can cause mismatches. The execution table shows each step and its result, while the variable tracker follows the model and database schema changes. Remember to always migrate after model changes and upgrade to apply them.

Practice

(1/5)
1. What is the main purpose of Flask-Migrate in a Flask application?
easy
A. To handle user authentication and sessions
B. To create HTML templates for the Flask app
C. To manage database schema changes safely using migrations
D. To serve static files like CSS and JavaScript

Solution

  1. Step 1: Understand Flask-Migrate's role

    Flask-Migrate is a tool that helps manage changes to the database structure over time.
  2. Step 2: Identify the correct purpose

    It uses migrations to safely update the database schema without losing data.
  3. Final Answer:

    To manage database schema changes safely using migrations -> Option C
  4. Quick Check:

    Flask-Migrate = database migrations [OK]
Hint: Flask-Migrate is about database schema changes [OK]
Common Mistakes:
  • Confusing Flask-Migrate with template or static file handling
  • Thinking it manages user sessions
  • Assuming it creates HTML or CSS files
2. Which command correctly initializes Flask-Migrate in your Flask project?
easy
A. flask db init
B. flask migrate start
C. flask db create
D. flask migrate init

Solution

  1. Step 1: Recall the initialization command

    The command to set up Flask-Migrate for the first time is flask db init.
  2. Step 2: Check other options

    Other commands like flask migrate start or flask db create are incorrect or do not exist.
  3. Final Answer:

    flask db init -> Option A
  4. Quick Check:

    Initialize Flask-Migrate = flask db init [OK]
Hint: Use 'flask db init' to start migrations [OK]
Common Mistakes:
  • Using 'flask migrate init' instead of 'flask db init'
  • Confusing 'start' with 'init'
  • Trying commands that don't exist in Flask-Migrate
3. Given the following commands run in order:
flask db init
flask db migrate -m "Add users table"
flask db upgrade

What is the effect on the database?
medium
A. No changes happen until the app restarts
B. The database is reset and all data is lost
C. Only a migration script is created but not applied
D. The database schema is updated with the new users table

Solution

  1. Step 1: Understand each command's role

    flask db init sets up migration files, flask db migrate creates a migration script, and flask db upgrade applies changes to the database.
  2. Step 2: Determine the final effect

    After running all three, the database schema is updated with the new users table as described in the migration.
  3. Final Answer:

    The database schema is updated with the new users table -> Option D
  4. Quick Check:

    Upgrade applies migration = schema updated [OK]
Hint: Upgrade applies migration changes to DB [OK]
Common Mistakes:
  • Thinking upgrade resets the database
  • Believing migrate alone applies changes
  • Assuming changes need app restart
4. You run flask db migrate but see no new migration script created. What is the most likely cause?
medium
A. You forgot to run flask db init first
B. No changes detected in the models since last migration
C. The database server is down
D. You need to restart the Flask app

Solution

  1. Step 1: Understand what triggers migration scripts

    flask db migrate creates a script only if it detects changes in the database models.
  2. Step 2: Identify the cause of no new script

    If no changes are found, no new migration script is generated, which is the most common reason.
  3. Final Answer:

    No changes detected in the models since last migration -> Option B
  4. Quick Check:

    No model changes = no migration script [OK]
Hint: No model changes means no migration script [OK]
Common Mistakes:
  • Assuming database server status affects migration script creation
  • Thinking app restart is needed for migrations
  • Forgetting to initialize migrations (less common if already done)
5. You want to rename a column in your database using Flask-Migrate. Which sequence of steps is correct?
hard
A. Update the model's column name, run flask db migrate, then flask db upgrade
B. Run flask db upgrade first, then update the model, then flask db migrate
C. Delete the old column manually, update the model, then run flask db migrate
D. Update the model, restart Flask app, then run flask db upgrade

Solution

  1. Step 1: Change the model to reflect the new column name

    Modify your SQLAlchemy model to rename the column as desired.
  2. Step 2: Create and apply migration

    Run flask db migrate to generate the migration script, then flask db upgrade to apply it to the database.
  3. Final Answer:

    Update the model's column name, run flask db migrate, then flask db upgrade -> Option A
  4. Quick Check:

    Model change + migrate + upgrade = rename column [OK]
Hint: Change model first, then migrate and upgrade [OK]
Common Mistakes:
  • Running upgrade before migrate
  • Manually deleting columns instead of migrating
  • Restarting app without migration commands
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard