Guide 7 · Relational and Document Databases

SQLModel, Deep Dive

A Pydantic model and a database table in one class, and the places that convenience stops.

Complete 14 notebooks 14 written

Before this guide: APIs and JSON, and SQLAlchemy, Deep Dive.

The notebooks

Open in Colab runs a notebook in your browser, and Read shows it on GitHub without running it. Every notebook runs on its own, and the answers to its exercises are in a separate notebook, linked as Solutions.

1table=TrueThe schema and the model in one class, and the table that is already definedOpen in ColabReadSolutions
2Engine and create_allSQLModel.metadata.create_all, no such table, and the foreign keys SQLite ignoresOpen in ColabReadSolutions
3Sessionssqlmodel.Session, expire_on_commit, and the id that was still NoneOpen in ColabReadSolutions
4Field Types and Defaultsdatetime, Enum, UUID, and the dict that has no matching SQLAlchemy typeOpen in ColabReadSolutions
5Reading Rowssession.exec, one() when two rows match, and the Row tuple you did not expectOpen in ColabReadSolutions
6Validation and table=TrueThe validator that silently never ran on your table modelOpen in ColabReadSolutions
7Create, Read and Update Modelsmodel_validate, sqlmodel_update, and the update that wrote None over every fieldOpen in ColabReadSolutions
8Relationshipsback_populates, cascade_delete, and the heroes orphaned by a deleted teamOpen in ColabReadSolutions
9Many to ManyLink models, a composite primary key, and the extra column that landed NULLOpen in ColabReadSolutions
10Loading and N+1sa_relationship_kwargs, and the 200 queries hiding behind one loopOpen in ColabReadSolutions
11sa_column and __table_args__Real column types, unique constraints, and where SQLModel hands you back to SQLAlchemyOpen in ColabReadSolutions
12MigrationsThe import Alembic leaves out of the script it generates, and the column create_all will never addOpen in ColabReadSolutions
13SQLModel in FastAPIA session dependency, response_model, and the response that referred to itselfOpen in ColabReadSolutions
14A Small ServiceTable models, public models, a migration, and a tested API in one notebookOpen in ColabReadSolutions