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:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_columnclass 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:
from sqlalchemy import selectwith Session(engine) as session:session.add(Student(name="Ana", package=7.5)) # INSERTsession.commit()top = session.scalars(select(Student).where(Student.package > 7) # SELECT … WHERE).all()
When to use an ORM
Key takeaways
- 01An ORM maps classes to tables and objects to rows.
- 02SQLAlchemy is the de-facto Python ORM; models are typed classes.
- 03A Session tracks changes; you add/query objects and it generates SQL.
- 04Pros: less boilerplate, database-agnostic; cons: learning curve, N+1 pitfalls.
- 05Use the ORM for CRUD; drop to raw SQL for complex queries.
