API Reference

SQLModel

Library combining Pydantic and SQLAlchemy so one Python class defines both a model and a table.

Official Documentation ↗
CompatibilityThis documentation covers version sqlmodel 0.0.16+ / SQLAlchemy 2.x / Python 3.9+. Check the official docs for the latest API surface.

Installation

pippip install sqlmodel

Methods

Overview

SQLModel unifies data validation and database modeling by building on Pydantic and SQLAlchemy. A single typed class can validate request data and map to a table, reducing duplication.

Core Methods

Subclass SQLModel and set table=True to define a table. create_engine builds the connection, metadata.create_all creates tables, and Session plus select read and write rows.

Usage Notes

Use separate non-table models for create and read responses to control which fields are exposed. Manage schema changes with Alembic, and keep sessions short.

Common Pitfalls

create_all does not alter existing tables, so production schema changes need migrations. Accessing lazy relationships after the session closes raises errors. Field types must map cleanly onto the chosen database.

FAQ

How does SQLModel relate to Pydantic and SQLAlchemy?
SQLModel classes are Pydantic models used for validation and serialization and, when table=True, also SQLAlchemy table definitions, so one class serves API and database layers.
How do I run migrations?
SQLModel creates tables for development convenience but does not manage schema evolution. Use Alembic to generate and apply migrations in production.
How do relationships work?
Relationships use Relationship fields with back_populates, similar to SQLAlchemy. Load lazy relationships within an open session or configure eager loading to avoid detached errors.