Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
A Post model, a SQLite file in the instance folder, and the exact SQL Flask-Migrate runs. Plus a two-run script that shows why create_all never adds a column, and two posts saved and read back from flask shell.
What you will learn
- Write a Flask-SQLAlchemy model with Mapped type hints and connect it with init_app
- Explain why db.create_all() can't change an existing table
- Create, preview and apply a migration with flask db migrate, upgrade --sql and upgrade
- Save and read rows through db.session in a route and in flask shell
Before you start
- Flask routes and templates
- Basic SQL tables and rows
Until now our Flask app kept nothing. Stop the server, and anything we sent it was gone. A database keeps it, even after a restart. A model tells Python what that data looks like.
We'll use SQLite throughout this track. It's a database kept in a single file, blog.db, so there's no database server to install. Inside it there will be a table called posts with four columns: id, title, body and created. We won't write that SQL by hand. With SQLAlchemy, one Python class stands for the table, and one object of that class becomes one row. That's an ORM, an object relational mapper. (If you want a SQL refresher first, see SQL essentials.)
Two more bricks
Flask itself is small, and you snap on extensions for what you need. Today we snap on two:
- Flask-SQLAlchemy connects SQLAlchemy to the app, so models and sessions work inside Flask.
- Flask-Migrate brings in Alembic, the tool that writes and runs migrations.
uv add flask-sqlalchemy flask-migrate
Resolved 14 packages in 21ms
Installed 6 packages in 205ms
+ alembic==1.20.1
+ flask-migrate==4.1.0
+ flask-sqlalchemy==3.1.1
+ mako==1.4.3
+ sqlalchemy==2.1.8
+ typing-extensions==4.16.0
uv tree --depth 1 shows three direct packages: flask v3.1.3, flask-migrate v4.1.0 and flask-sqlalchemy v3.1.1.
The Post model
models.py:
from datetime import datetime, timezone
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import DateTime, String, Text
from sqlalchemy.orm import (DeclarativeBase, Mapped,
mapped_column)
def now():
return datetime.now(timezone.utc)
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)
class Post(db.Model):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
body: Mapped[str] = mapped_column(Text)
created: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=now)
Baseis built fromDeclarativeBase. SQLAlchemy uses it to keep a list of every table.db = SQLAlchemy(model_class=Base)is the handle to the models, the session and the queries. It doesn't get the app yet; that happens inmain.py.__tablename__ = "posts". Without it, Flask-SQLAlchemy would name the tablepost, from the class name.idis the primary key, so the database numbers each row.titleholds up to 200 characters, andbodyisTextfor longer writing.createddefaults tonow(), which callsdatetime.now(timezone.utc). Older code often usesdatetime.utcnow, but that one is deprecated.
The type hints matter. Mapped[int] and Mapped[str] tell SQLAlchemy each column's type and that it can't be empty.
Connecting it to the app
from flask import Flask, jsonify, request
from flask_migrate import Migrate
from models import Post, db
app = Flask(__name__)
app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:///blog.db")
db.init_app(app)
migrate = Migrate(app, db)
With a short path like sqlite:///blog.db, Flask-SQLAlchemy puts the file in the instance folder, so it ends up as instance/blog.db. That folder is for files that belong to this one copy of the app, not to the code. db.init_app(app) connects the db object to this app, and Migrate(app, db) adds a new group of commands called flask db.
Why create_all isn't enough
The quick way to make tables is db.create_all(). It creates any table that's missing, and that's all it does. The lecture checks this with a small script, check_all.py, whose Post gets an extra author column only when you pass an argument:
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
app = Flask(__name__)
app.config.update(
SQLALCHEMY_DATABASE_URI="sqlite:///check.db")
db = SQLAlchemy(app)
class Post(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
if len(sys.argv) > 1:
author: Mapped[str] = mapped_column(String(80))
with app.app_context():
db.create_all()
cols = db.session.execute(
db.text("PRAGMA table_info(post)")).all()
print([c[1] for c in cols])
uv run python check_all.py
uv run python check_all.py author
['id', 'title']
['id', 'title']
The second run's class has an author column, but the table already exists, so create_all leaves it alone. author never shows up.
Migrations solve this. Each migration is a small file with one step, like "create the posts table" or "add a column". The files are chained in order, and the database keeps a note of the last step it ran. Any copy of the database, yours or a teammate's, can be brought up to date the same way.
flask db init
uv run flask --app main db init
Creating directory S01L02_2_Models\migrations ... done
Creating directory S01L02_2_Models\migrations\versions ... done
Generating S01L02_2_Models\migrations\alembic.ini ... done
Generating S01L02_2_Models\migrations\env.py ... done
Generating S01L02_2_Models\migrations\README ... done
Generating S01L02_2_Models\migrations\script.py.mako ... done
Please edit configuration/connection/logging settings in S01L02_2_Models\migrations\alembic.ini before proceeding.
With Flask-Migrate you can skip that last line. env.py takes the database address from your app's config, so there's only one place to change it. You run init once per project, and the migrations folder stays in the project with the rest of the code.
flask db migrate writes a draft
uv run flask --app main db migrate -m "create posts table"
Flask-Migrate compares the models with the database. The important log line is near the end:
INFO [alembic.autogenerate.compare.tables] Detected added table 'posts'
A new file appears in migrations/versions, named after the revision id and your message:
"""create posts table
Revision ID: 002c58deb75d
Revises:
Create Date: 2026-11-15 18:25:04.014356
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '002c58deb75d'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=200), nullable=False),
sa.Column('body', sa.Text(), nullable=False),
sa.Column('created', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('posts')
# ### end Alembic commands ###
upgrade creates the table with every column, each nullable=False. downgrade does the opposite, so you can step back. down_revision = None because this is the first step in the chain. Treat this file as a draft and read it before you run it, the same way you review a diff from an AI agent.
See the SQL before it runs
uv run flask --app main db upgrade --sql
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL,
CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num)
);
-- Running upgrade -> 002c58deb75d
CREATE TABLE posts (
id INTEGER NOT NULL,
title VARCHAR(200) NOT NULL,
body TEXT NOT NULL,
created DATETIME NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO alembic_version (version_num) VALUES ('002c58deb75d') RETURNING version_num;
With no revision given, upgrade goes to the latest step, called head. First comes the small alembic_version table, where the database keeps its note. Then your model in plain SQL. Last, the revision id goes into alembic_version. With --sql nothing has run yet. It only prints.
Upgrade, current, history
uv run flask --app main db upgrade
uv run flask --app main db current
uv run flask --app main db history
INFO [alembic.runtime.migration] Running upgrade -> 002c58deb75d, create posts table
002c58deb75d (head)
<base> -> 002c58deb75d (head), create posts table
instance/blog.db now has two tables, alembic_version and posts. When the model changes, it's the same two commands again: flask db migrate, then flask db upgrade.
One note for later: the finished blog in this track has no migrations tool, and it ships two one-off scripts in its root (delete_admin.py and reset_admin_password.py). Migrations for the tables, and a proper admin command, are what replace scripts like those. You'll meet them in the Flask blog folder tour.
Saving and reading posts
def as_dict(post):
return {"id": post.id, "title": post.title,
"body": post.body,
"created": post.created.isoformat()}
@app.post("/posts")
def create_post():
data = request.get_json()
post = Post(title=data["title"], body=data["body"])
db.session.add(post)
db.session.commit()
return jsonify(as_dict(post)), 201
@app.get("/posts")
def list_posts():
posts = db.session.scalars(db.select(Post)).all()
return jsonify([as_dict(p) for p in posts])
@app.post and @app.get are the short way to write a route for one method. request.get_json() turns the JSON body into a dict. db.session.add puts the new object in the session, which is one conversation with the database; Flask-SQLAlchemy gives each request its own and cleans it up when the request ends. commit writes the row, and the post gets its id and created time. jsonify makes JSON, and 201 means created.
Two POSTs and a GET from the run:
POST /posts {"title": "Hello", "body": "My first post."}
201 {"body":"My first post.","created":"2026-11-15T18:25:27.219862","id":1,"title":"Hello"}
POST /posts {"title": "Packing a bag", "body": "Light is best."}
201 {"body":"Light is best.","created":"2026-11-15T18:25:27.295962","id":2,"title":"Packing a bag"}
GET /posts
200 [{"body":"My first post.","created":"2026-11-15T18:25:27.219862","id":1,"title":"Hello"},{"body":"Light is best.","created":"2026-11-15T18:25:27.295962","id":2,"title":"Packing a bag"}]
db.session.scalars(db.select(Post)) gives Post objects rather than raw rows, and .all() makes a list. Notice created comes back without a time zone offset: SQLite has no time zone type. We saved it in UTC, so we know what it means.
Reading the file from flask shell
Those posts are in the file now, not in the app's memory. flask shell is a Python prompt with the app already loaded:
uv run flask --app main shell
from models import Post, db
posts = db.session.scalars(db.select(Post)).all()
print(len(posts))
print([p.title for p in posts])
first = db.session.get(Post, 1)
print(first.title, first.created.year > 2000)
2
['Hello', 'Packing a bag']
Hello True
db.session.get(Post, 1) fetches one row by its id. The shell's header names the app, main, and the instance folder where blog.db lives. The same file answered from a separate process, not through the server.
Common mistakes
- Relying on
create_allfor changes. It never alters an existing table. - Running a migration you haven't read. Autogenerate is a draft; check it, and use
upgrade --sqlto see the SQL. - Looking for
blog.dbnext tomain.py. A relative SQLite path lands ininstance/. - Forgetting
commit().add()alone doesn't write the row. - Using
datetime.utcnow. It's deprecated; usedatetime.now(timezone.utc).
Quick recap
| Step | Command or code |
|---|---|
| model | class Post(db.Model) with Mapped[...] columns |
| connect | db.init_app(app), Migrate(app, db) |
| set up once | flask db init |
| write a migration | flask db migrate -m "..." |
| preview / apply | flask db upgrade --sql / flask db upgrade |
| check | flask db current, flask db history |
| write and read | db.session.add + commit; db.session.scalars(db.select(Post)) |
Try it yourself
Add an optional summary column to Post, as Mapped[str | None]. Run flask db migrate and flask db upgrade, and read the migration file it makes. What does its down_revision say now?
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
