SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.
npx @tessl/cli install tessl/pypi-sqlmodel@0.0.0SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust. SQLModel is based on Python type annotations, and powered by Pydantic and SQLAlchemy.
The key innovation of SQLModel is that it allows you to define a single class that serves as both a SQLAlchemy table model and a Pydantic validation model, eliminating code duplication and ensuring consistency across database operations and API interfaces.
pip install sqlmodelfrom sqlmodel import SQLModel, Field, Relationship, Session, create_engine, selectAdditional commonly used imports:
# SQL operations and expressions
from sqlmodel import and_, or_, not_, func, text, Column, Index, ForeignKey
# Data types
from sqlmodel import String, Integer, Boolean, DateTime, Float, Text
# Engine and connection management
from sqlmodel import create_mock_engine, MetaData, inspectfrom typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
# Define a model that works as both SQLAlchemy table and Pydantic model
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
# Create database engine and tables
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)
# Create and save data
hero = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
with Session(engine) as session:
session.add(hero)
session.commit()
# Query data with type safety
with Session(engine) as session:
statement = select(Hero).where(Hero.name == "Spider-Boy")
result = session.exec(statement).first()
print(result) # Hero object with full type supportSQLModel combines three key technologies:
The SQLModel class serves as a bridge between these systems, allowing a single model definition to work seamlessly with both database operations and API serialization, particularly in FastAPI applications.
Core functionality for defining database models that work with both SQLAlchemy and Pydantic, including field definitions and relationships.
class SQLModel(BaseModel, metaclass=SQLModelMetaclass): ...
def Field(
default: Any = ...,
*,
primary_key: bool = False,
foreign_key: Optional[str] = None,
unique: bool = False,
nullable: Optional[bool] = None,
index: Optional[bool] = None,
**kwargs
) -> Any: ...
def Relationship(
*,
back_populates: Optional[str] = None,
cascade_delete: bool = False,
**kwargs
) -> Any: ...Database session handling with enhanced typing support for better type inference with SQLModel objects.
class Session(SQLAlchemySession):
def exec(self, statement: Select[T]) -> Result[T]: ...Query building and execution with type-safe SELECT statements and SQL expression functions.
def select(*entities) -> Union[Select, SelectOfScalar]: ...
def and_(*clauses) -> BooleanClauseList: ...
def or_(*clauses) -> BooleanClauseList: ...
def not_(clause) -> UnaryExpression: ...Database engine creation and connection management, re-exported from SQLAlchemy with full compatibility.
def create_engine(url: str, **kwargs) -> Engine: ...
def create_mock_engine(dialect: str, executor: Callable) -> MockConnection: ...Database schema components including tables, columns, constraints, and indexes, providing full SQLAlchemy schema definition capabilities.
class MetaData: ...
class Table: ...
class Column: ...
class Index: ...
class ForeignKey: ...Comprehensive SQL data type system with Python type mapping, including both SQLAlchemy standard types and SQLModel extensions.
class AutoString(TypeDecorator): ...
# Standard SQLAlchemy types
Integer: TypeEngine
String: TypeEngine
DateTime: TypeEngine
Boolean: TypeEngineclass FieldInfo(PydanticFieldInfo):
primary_key: bool
nullable: Optional[bool]
foreign_key: Any
unique: bool
index: Optional[bool]
sa_type: Any
sa_column: Optional[Column]
class RelationshipInfo:
back_populates: Optional[str]
cascade_delete: bool
passive_deletes: Union[bool, Literal["all"]]
link_model: Optional[Any]
class SQLModelMetaclass(ModelMetaclass, DeclarativeMeta): ...