SQLModel

0.0.38 · active · verified Mon Apr 06

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.

Warnings

Install

Imports

Quickstart

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()

view raw JSON →