ORMs with SQLAlchemy
What is an ORM?
An Object-Relational Mapper lets you work with database rows as Python objects: tables become classes, rows become instances, and queries become method calls. SQLAlchemy is the most popular one for Python.
Why use one
- Less raw SQL and fewer typos.
- Switch databases (SQLite → PostgreSQL) by changing one connection string.
- Relationships (
user.orders) and data validation in one place.
SQLAlchemy 2.0 style
- Models: subclass
DeclarativeBaseand useMapped[...]withmapped_column(). create_engine("sqlite:///app.db")connects.Base.metadata.create_all(engine)creates the tables.Sessionadds, commits and queries:session.scalars(select(User).where(...)).
Trade-offs
ORMs hide SQL, which can lead to slow queries if you don't understand what they generate. Learn basic SQL first (previous lesson), then use the ORM.
▶️ Runs in the app (the first run downloads SQLAlchemy).
Example
from sqlalchemy import create_engine, select, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
score: Mapped[int] = mapped_column(default=0)
def __repr__(self):
return f"User({self.name!r}, {self.score})"
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([User(name="Ana", score=90), User(name="Ben", score=72)])
session.commit()
top = session.scalars(select(User).where(User.score >= 80)).all()
print(top) # [User('Ana', 90)]