Registry / database / sqlmodel

sqlmodel

JSON →
library0.0.39pypypi✓ verified 25d ago

SQLModel is a Python library that unifies SQLAlchemy's ORM capabilities with Pydantic's data validation, simplifying interaction with SQL databases. It aims to reduce code duplication by using a single class definition for both database models and data schemas. SQLModel is currently in version 0.0.38 and maintains an active development cadence with frequent releases, often including bug fixes, dependency updates, and sometimes breaking changes.

pip install sqlmodel
INSTALL
IMPORT
SIG · SQLMODEL
S
sqlmodel
databasepythonv0.0.39
Install
4.9s avg
Import
1108ms
Disk
51MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.0.39 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 1.159s · 53.1MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 4.9s · import 1.058s · 50MB
51MB installed
● package 51MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SQLModel
from sqlmodel import SQLModel
Field
from sqlmodel import Field
Session
from sqlmodel import Session
create_engine
from sqlmodel import create_engine
select
from sqlmodel import select
from sqlalchemy import select
SQLModel's `select` provides enhanced type annotations and automatically handles `.scalars()` which SQLAlchemy's version doesn't.
create_async_engine
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import create_async_engine
Async engine is imported directly from SQLAlchemy's async extension.
AsyncSession
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import AsyncSession
Async session is imported directly from SQLAlchemy's async extension.

This quickstart demonstrates how to define a `SQLModel` table, create a database engine (using SQLite in this case), create the database tables, and then insert and query data. It showcases the combined power of Pydantic-like model definition with SQLAlchemy's ORM operations. The `echo=True` in `create_engine` will print SQL statements to the console.

from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" # Or for in-memory: # sqlite_url = "sqlite://" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", age=16) hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.commit() session.refresh(hero_1) session.refresh(hero_2) session.refresh(hero_3) print("Created heroes:", hero_1, hero_2, hero_3) def select_heroes(): with Session(engine) as session: statement = select(Hero).where(Hero.age >= 18) results = session.exec(statement) heroes = results.all() print("Adult heroes:", heroes) def main(): create_db_and_tables() create_heroes() select_heroes() if __name__ == "__main__": main()
Debug
Known issues
breakingSQLModel versions 0.0.35 and higher require Python 3.10 or later.
fix
Upgrade your Python environment to 3.10 or newer. For older Python versions, use SQLModel < 0.0.35.
affects: >=0.0.35
breakingSQLModel version 0.0.31 dropped support for Pydantic v1. It now requires Pydantic v2.
fix
Upgrade Pydantic to version 2 (e.g., `pip install pydantic==2.*`). Be aware that Pydantic v2 has its own breaking changes. If you must use Pydantic v1, pin SQLModel to `<0.0.31` or use `pydantic<2`.
affects: >=0.0.31
gotchaSQLModel `Session` objects are not thread-safe and should be created per request/task, typically using a `with Session(engine) as session:` block. Detached objects (queried in one session, then used in another) can lead to unexpected behavior.
fix
Always use a new `Session` context manager for each logical unit of work. For FastAPI, use `Depends` to inject a session per request. Ensure all operations on a model instance occur within the same session that loaded it.
affects: all
gotchaFor asynchronous database operations, you must use `sqlalchemy.ext.asyncio.create_async_engine` and `sqlalchemy.ext.asyncio.AsyncSession` (or `sqlmodel.ext.asyncio.Session` when available). Also, ensure you use an async-compatible database driver (e.g., `aiosqlite` for SQLite, `asyncpg` for PostgreSQL).
fix
Install the correct async driver (e.g., `pip install sqlmodel[aiosqlite]`). Use `create_async_engine` with a proper async database URL (e.g., `sqlite+aiosqlite:///./test.db`). Manage async sessions with `async with AsyncSession(engine) as session:`.
affects: all
gotchaThe `SQLModel.metadata.create_all(engine)` call must be executed *after* all your `SQLModel` classes have been defined. If models are in separate files, ensure they are imported before `create_all` is called.
fix
Structure your code so model definitions are fully loaded before `SQLModel.metadata.create_all()` is invoked. For complex applications, consider using a database migration tool like Alembic.
affects: all
gotchaWhen defining relationships between models (e.g., `Hero` and `Team`), circular import issues can arise with type annotations. Python's runtime cannot resolve these.
fix
Use `from typing import TYPE_CHECKING` and import classes inside an `if TYPE_CHECKING:` block for type-checking tools. For example: `if TYPE_CHECKING: from .other_model import OtherModel`.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'sqlmodel'
The sqlmodel library has not been installed in the current Python environment.
fix
pip install sqlmodel
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgresql
The specific database driver required for the chosen database dialect (e.g., psycopg2-binary for PostgreSQL, aiosqlite for async SQLite, mysqlclient for MySQL) is not installed.
fix
pip install psycopg2-binary (replace 'psycopg2-binary' with the appropriate driver for your database, e.g., 'aiosqlite' for SQLite, 'mysqlclient' for MySQL)
ValueError: Field 'id' has a default value, but is not marked as optional.
A primary key field with an auto-incrementing default (typically None) must be explicitly typed as Optional to satisfy both Pydantic's validation and SQLAlchemy's ORM requirements.
fix
Define the field using Optional and Field(default=None, primary_key=True), for example: id: Optional[int] = Field(default=None, primary_key=True)
AttributeError: 'Table' object has no attribute 'c'
Users are attempting to access SQLAlchemy Core constructs like .__table__.c directly on a SQLModel class or instance, which are not directly exposed or are handled differently in SQLModel's higher-level API.
fix
For queries, use SQLModel's direct attribute access, e.g., select(Hero.name) or session.exec(select(Hero).where(Hero.name == 'Deadpond')) instead of SQLAlchemy Core syntax. If a raw Table object is truly needed, access SQLModelClass.__table__.
Upgrade
Version history
0.0.39latest on PyPI · released Jun 25, 2026
Audit
Dependencies
pydanticrequiredCore dependency for data validation and schema definition, version 2+ is required.
sqlalchemyrequiredCore dependency for ORM and database interaction, version 2+ is recommended.
fastapioptionalOften used together for building APIs, offers seamless integration.
asyncpgoptionalAsynchronous PostgreSQL driver for async database operations.
aiosqliteoptionalAsynchronous SQLite driver for async database operations.
Agent activity
44 hits · last 30 days
node
40
Meta
1
OpenAI (training)
1
Resources
sqlmodel — pip install sqlmodel · libregistry