SQLModel Setup
Describe a table once with SQLModel - a class that is both a SQLAlchemy table and a Pydantic model. Create the engine and the table, save and read rows with a Session, and split the model into Base, table, Create and Public models. Tested with the traps: table models do not validate, objects expire after commit, and create_all never changes an existing table.
What you will be able to do
- Define a table with SQLModel and table=True
- Create the engine and the tables
- Save, read and filter rows with a Session
- Split one resource into Base, table, Create and Public models
- Know why table models do not validate input
- Avoid using objects after their session is closed
The idea, in plain English
SQLModel joins two libraries you already met. A SQLModel class with table=True is a SQLAlchemy table (the ORM) and a Pydantic model at the same time. So one class describes the columns in the database and the fields in the JSON.
Three pieces work together. The engine knows how to reach the database - one per app. The table classes describe the tables, and create_all makes them. A Session is one unit of work: you add objects, commit, and read with select().
We set up the to-do table from Module 1, fill it from a script, look at it with the sqlite3 tool, and try the traps before we connect it to FastAPI in Lesson 5.3. SQLModel 0.0.48, SQLAlchemy 2.1.4, Pydantic 2.14.
Worked example: A Todo table in a SQLite file, filled and read from a small script - the base for the to-do API in Lesson 5.3.
1 - Check the input
TodoCreate checks the client data. Todo.model_validate makes the table object.
From client data to a saved row and back. Real results from first_steps.py.
Words you will see in this lesson
A few SQLModel words.
EngineThe object that knows how to connect to the database. One per app.Table modelA SQLModel class with table=True - it has a table in the database.Data modelA SQLModel class without table=True - a normal Pydantic model.SessionOne unit of work: add objects, commit, read.create_allCreates every table that does not exist yet.RefreshRead an object’s values again from the database.An everyday example: a bank branch
- The bank’s address and phone number is the engine - everyone uses the same one.
- The account form layout is the table model - it decides the columns.
- A visit to the counter is a session: you hand in several forms, and at the end the clerk stamps them all at once (commit).
- The form you fill in (TodoCreate) and the statement you receive (TodoPublic) are different papers, made from the same account.
Example 1 - the models
models.py describes one resource with four classes (the pattern from Lesson 2.5):
- TodoBase - the shared fields, with rules: title 1-100 characters, done False by default. Not a table.
- Todo(TodoBase, table=True) - the table. It adds id (the primary key; None until the database gives one) and created_at (made when the object is created, in UTC).
- TodoCreate - what a client may send. No id, no created_at.
- TodoPublic - what a client gets back. id is int here, not "int | None".
from datetime import datetime, timezone
from sqlmodel import Field, SQLModel
class TodoBase(SQLModel): # the shared fields - NOT a table
title: str = Field(min_length=1, max_length=100)
done: bool = False
class Todo(TodoBase, table=True): # the table
id: int | None = Field(default=None, primary_key=True)
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
class TodoCreate(TodoBase): # what a client sends
pass
class TodoPublic(TodoBase): # what a client gets back
id: int
created_at: datetimeExample 2 - the engine and the first rows
db.py makes one engine for the app and a function that creates the tables. first_steps.py uses them:
- 1. TodoCreate(title="Buy milk") checks the input.
- 2. Todo.model_validate(data) makes a table object from it.
- 3. session.add(todo) says "save this" - nothing is sent yet.
- 4. session.commit() sends the INSERT and makes it permanent.
- 5. session.refresh(todo) reads the row back, so todo.id is filled.
- session.get(Todo, 2) finds one row by primary key; a missing id gives None.
- session.exec(select(Todo).where(...).order_by(...)).all() gives a list of Todo objects.
- TodoPublic.model_validate(todo) turns the table object into the public model.
from sqlmodel import SQLModel, create_engine
engine = create_engine("sqlite:///todos.db") # one engine for the whole app
def create_tables():
SQLModel.metadata.create_all(engine) # makes the tables that do not exist yetfrom sqlmodel import Session, select
from db import create_tables, engine
from models import Todo, TodoCreate, TodoPublic
create_tables()
with Session(engine) as session:
data = TodoCreate(title="Buy milk") # 1. checked input
todo = Todo.model_validate(data) # 2. a table object from it
print("before commit: id =", todo.id)
session.add(todo) # 3. "please save this"
session.commit() # 4. INSERT + COMMIT
session.refresh(todo) # 5. read it back (id, created_at)
print("after commit: id =", todo.id)
session.add(Todo(title="Pay rent"))
session.add(Todo(title="Call mom", done=True))
session.commit()
print("get(2): ", session.get(Todo, 2))
print("get(99): ", session.get(Todo, 99))
rows = session.exec(select(Todo).where(Todo.done == False).order_by(Todo.title)).all() # noqa: E712
print("open: ", [t.title for t in rows])
print("public: ", TodoPublic.model_validate(todo).model_dump_json())before commit: id = None
after commit: id = 1
get(2): done=False title='Pay rent' id=2 created_at=datetime.datetime(2026, 10, 12, 17, 6, 34, 183135, tzinfo=datetime.timezone.utc)
get(99): None
open: ['Buy milk', 'Pay rent']
public: {"title":"Buy milk","done":false,"id":1,"created_at":"2026-10-12T17:06:34.181335Z"}The table in the file
sqlite3 todos.db ".schema todo" shows what create_all made:
- title VARCHAR(100) NOT NULL - max_length=100 became the column size.
- done BOOLEAN NOT NULL and created_at DATETIME NOT NULL - from the Python types.
- id INTEGER NOT NULL with PRIMARY KEY (id) - from primary_key=True.
- min_length=1 is NOT in the table - only Pydantic checks it.
CREATE TABLE todo (
title VARCHAR(100) NOT NULL,
done BOOLEAN NOT NULL,
id INTEGER NOT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id)
);Trap 1: a table model does not check its data
- Todo(title="", done="maybe") gave no error. The object had an empty title and done = "maybe".
- TodoCreate(title="", done="maybe") refused both fields: 2 errors.
- SQLModel does not validate table=True models when you create them.
- Rule: check client data with a data model (TodoCreate), then make the table object with Todo.model_validate(data).
from sqlmodel import Session
from db import engine
from models import Todo, TodoCreate
# Trap 1: a table model does not check its data
bad = Todo(title="", done="maybe")
print("table model:", repr(bad.title), repr(bad.done))
try:
TodoCreate(title="", done="maybe")
except Exception as e:
print("TodoCreate: ", e.error_count(), "errors:", [err["loc"][0] for err in e.errors()])
# Trap 2: using an object after its session is closed
with Session(engine) as session:
todo = Todo(title="Water plants")
session.add(todo)
session.commit() # commit "expires" the object
try:
print(todo.title)
except Exception as e:
print("after close:", type(e).__name__ + ":", str(e)[:110])table model: '' 'maybe'
TodoCreate: 2 errors: ['title', 'done']
after close: DetachedInstanceError: Instance <Todo at 0x103981f40> is not bound to a Session; attribute refresh operation cannot proceed (BackgrouTrap 2: objects after the session is closed
Look at the last line of that output:
- After commit, the session marks its objects as "expired": the next attribute read loads fresh values from the database.
- But the session was already closed. todo.title raised DetachedInstanceError.
- Rule: use objects inside the session - or call session.refresh(todo) before it closes, as first_steps.py did.
- In FastAPI (Lesson 5.3) the session lives for the whole request, so this mostly happens in scripts and background jobs.
Dates are stored in UTC
We saved a to-do with 10:00 Indian time (+05:30) and read it back in a new session:
- It came back as 04:30 UTC - the same moment, written in UTC.
- The file holds plain text without a time zone: 2026-10-12 04:30:00.000000.
- So always create times with a time zone (datetime.now(timezone.utc)), and convert to local time only when you show them.
sent: 2026-10-12 10:00:00+05:30
read back: 2026-10-12 04:30:00+00:00
2026-10-12 04:30:00.000000Trap 3: create_all never changes a table
We added priority: int = 0 to the model and ran create_all again:
- create_all gave no error - the table already existed, so it did nothing.
- The first select failed: "no such column: todo.priority".
- create_all only creates missing tables. It never adds, removes or changes columns.
- While learning, delete the .db file and start again. With real data, use migrations (Lesson 5.5).
from datetime import datetime, timezone
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Todo(SQLModel, table=True): # the same table, one new field
id: int | None = Field(default=None, primary_key=True)
title: str = Field(min_length=1, max_length=100)
done: bool = False
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
priority: int = 0 # NEW
engine = create_engine("sqlite:///todos.db")
SQLModel.metadata.create_all(engine) # the table exists - nothing is changed
print("create_all: no error")
with Session(engine) as session:
try:
session.exec(select(Todo)).all()
except Exception as e:
print(type(e).__name__ + ":", str(e).splitlines()[0])create_all: no error
OperationalError: (sqlite3.OperationalError) no such column: todo.prioritySQLModel at a glance
TableColumns from fields.
class Todo(TodoBase, table=True):
id: int | None = Field(default=None, primary_key=True)EngineOne per app.
engine = create_engine("sqlite:///todos.db")TablesOnly missing ones.
SQLModel.metadata.create_all(engine)
SaveThen id is set.
session.add(todo); session.commit(); session.refresh(todo)
One by idNone if missing.
session.get(Todo, 2)
QueryA list of objects.
session.exec(select(Todo).where(Todo.done == False)).all()
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Add echo=True to create_engine in db.py and run first_steps.py again. Count the INSERTs.”
“Get todo 2, set done = True, add and commit it. Check with the sqlite3 tool.”
“session.delete(session.get(Todo, 3)) and commit. What does get(3) return now?”
“Delete todos.db, add the priority field, and run first_steps.py. Does .schema show it now?”
What usually goes wrong
Todo(title="", done="maybe") was accepted. Use TodoCreate first.
✗ todo = Todo(**client_data)✓ todo = Todo.model_validate(TodoCreate(**client_data))DetachedInstanceError. Refresh inside the session, or keep working inside it.
It only creates missing tables - "no such column" followed.
Use datetime.now(timezone.utc) so stored times are clear.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add a Tag table (id, name unique, max 30 characters) with TagBase, Tag, TagCreate and TagPublic. Write a script that adds three tags from TagCreate objects, refuses an empty name, and prints all tags sorted by name as TagPublic JSON. Then try to add a duplicate name and print the error.
Show hintHide hint
Field(unique=True) makes a UNIQUE column. The duplicate fails at commit with IntegrityError - call session.rollback() afterwards.
Key points
- A SQLModel class with table=True is both a table and a Pydantic model.
- One engine per app; create_all makes missing tables.
- A Session collects changes; commit saves them; refresh reads them back.
- Use Base, table, Create and Public models for one resource.
- Table models do not validate - check input with a data model first.
- create_all never changes an existing table.
Quick check before you move on
Interview questions
Why separate table models from input and output models?
Input models validate and limit what clients can set, output models control what is exposed, and table models map storage (and skip validation in SQLModel). Separation avoids mass-assignment bugs and leaking internal fields.
What does expire_on_commit do, and when does it bite?
After commit, loaded objects are marked stale so the next attribute access reloads them. Accessing them after the session closes raises DetachedInstanceError; refresh before closing, keep the session open, or disable expire_on_commit deliberately.
Quiz
- 1.
Why is id typed int | None in Todo but int in TodoPublic?
- 2.
Why did todo.title fail after the with block?
- 3.
Which rule from models.py is not in the table schema?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...