Skip to main content
Albero Academy

SQLAlchemy

Map Python classes to database tables with an ORM.

Databases11 min

An ORM (Object-Relational Mapper) lets you work with database rows as Python objects — no hand-written SQL for the common cases.SQLAlchemy is the de-facto Python ORM, powering everything from small apps to large systems.

Defining models

A class maps to a table; its typed attributes map to columns:

ORM models
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase): ...
class Student(Base):
__tablename__ = "students"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
package: Mapped[float]

Working with objects

You add, query and update Python objects; SQLAlchemy generates the SQL and tracks changes:

a session
from sqlalchemy import select
with Session(engine) as session:
session.add(Student(name="Ana", package=7.5)) # INSERT
session.commit()
top = session.scalars(
select(Student).where(Student.package > 7) # SELECT … WHERE
).all()

When to use an ORM

Key takeaways

  1. 01An ORM maps classes to tables and objects to rows.
  2. 02SQLAlchemy is the de-facto Python ORM; models are typed classes.
  3. 03A Session tracks changes; you add/query objects and it generates SQL.
  4. 04Pros: less boilerplate, database-agnostic; cons: learning curve, N+1 pitfalls.
  5. 05Use the ORM for CRUD; drop to raw SQL for complex queries.

Finished this chapter?

Mark it complete to track your progress through Python.