sqlalchemy

SQLAlchemy

SQL toolkit and ORM

Python
Libraries
Used by 442 projects
database
orm
sql

Details

Language / Topic
pythonPython
Category
Libraries

Rules

balanced
- Use the 2.0 style: `select(User).where(User.id == 1)` with `session.execute()` — avoid the legacy `session.query()` API.
- Use `sessionmaker` with `Session` context manager for transactions — commit explicitly and let `with` block handle rollback on exceptions.
- Define models with `DeclarativeBase` and `Mapped[T]` type annotations — use `relationship()` with `back_populates` for bidirectional associations.
- Use `Session` with context manager for transaction management: `with Session(engine) as session:`.
- Use `selectinload()` or `joinedload()` to prevent N+1 query patterns on relationships.
- Use `sessionmaker` with `expire_on_commit=False` for FastAPI/async contexts.
- Define relationships with `Mapped[list["Child"]]` and `relationship()` for type-safe navigation.