SQLModel Integration#

Advanced Alchemy provides built-in compatibility for SQLModel, allowing you to use SQLModel’s elegant syntax for defining models while leveraging Advanced Alchemy’s powerful repositories and services.

Basic Setup#

To use SQLModel with Advanced Alchemy, ensure your models are defined with table=True.

from typing import Optional
from sqlmodel import Field, SQLModel
from advanced_alchemy.repository import SQLAlchemyAsyncRepository

class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

class HeroRepository(SQLAlchemyAsyncRepository[Hero]):
    model_type = Hero
from sqlmodel import Field, SQLModel
from advanced_alchemy.repository import SQLAlchemyAsyncRepository

class Hero(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: int | None = None

class HeroRepository(SQLAlchemyAsyncRepository[Hero]):
    model_type = Hero

Usage with Repositories#

Repositories automatically detect SQLModel classes and handle them correctly during CRUD operations.

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

async def create_and_list_heroes() -> list[Hero]:
    engine = create_async_engine("sqlite+aiosqlite:///:memory:")
    async_session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)

    try:
        async with async_session_factory() as session:
            repo = HeroRepository(session=session)

            hero = Hero(name="Deadpool", secret_name="Dive Wilson")
            await repo.add(hero)
            await session.commit()

            return await repo.get_many()
    finally:
        await engine.dispose()

Limitations#

While SQLModel is supported, some Advanced Alchemy features that rely on specific SQLAlchemy base class behaviors (like some automated mixin detections) may require explicit configuration when used with SQLModel.