SQLModel¶
The SQLModel adapter builds on the SQLAlchemy adapter, so everything on that page applies. The differences:
- It is chosen automatically when your project imports
sqlmodel, and it replaces the plain SQLAlchemy adapter. - Table models (
table=True) are found through SQLModel's default registry, so they are loaded as soon as they are imported. Data-only models such asHeroReadare not. sessionis asqlmodel.Session(orsqlmodel.ext.asyncio.session.AsyncSession), sosession.exec()works.selectis SQLModel's version, andSQLModel,Field,Relationshipandcolare imported too.
Minimal setup¶
If you use FastAPI CLI, you may not need any config: with [tool.fastapi] entrypoint
set, the app is imported, which imports your models, and the engine is auto-detected.
Otherwise point fastapi-repl at your models and engine:
In the shell¶
heroes = session.exec(select(Hero).where(Hero.power > 5)).all()
hero = session.get(Hero, 1)
session.add(Hero(name="Spider-Boy", power=4))
session.commit()
With an async engine: