Backend Development with FastAPI
Back to Data Layer and Auth

SQLAlchemy 2.0 ORM

The modern SQLAlchemy: typed Mapped columns, declarative style, async support. The standard Python ORM. FIND_VIDEO: search 'sqlalchemy 2.0 tutorial mapped' — recommended channel: ArjanCodes / Mike Bayer talks. Aim for 11 min or under.

10 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. ORM Justification and Impedance Mismatch — The instructor explains the mismatch between objects and tables and introduces ORM as an abstraction layer.
  2. Declarative Base and Engine Setup — The video demonstrates defining the declarative base, modeling the Employee table, and binding the SQLite engine.
  3. Declarative Mapping and Schema Materialization — The instructor examines type annotation syntax and verifies table creation behavior using create_all.
  4. Transactional Data Insertion — The session context manager is used to stage and commit new Employee records to the database.
  5. Basic Data Retrieval — The video covers querying mapped objects across the session without needing transaction commits.
  6. Foreign Keys and Relational Integrity — The instructor adds a Department model and enforces relational constraints using ForeignKey.
  7. Object Hydration with Relationships — The lesson demonstrates using relationship attributes to navigate directly between connected entities.
  8. Architectural Decoupling with DTOs — The instructor highlights the risks of ORM coupling and shows how to decouple models using internal data classes.
PDF notes

Frequently asked questions

Why doesn't Base.metadata.create_all update a table when I add a new column?

create_all only emits CREATE TABLE for missing tables; it never inspects or alters existing database structures.

Do I need to call session.commit() when retrieving data with session.query()?

No, commit is only required to persist write operations like inserts, updates, and deletes.

What is the difference between ForeignKey and relationship in SQLAlchemy?

ForeignKey defines the database-level relational constraint, while relationship provides the Python attribute used to navigate between linked objects.

Why should I convert ORM models to Data Classes (DTOs)?

Converting to DTOs isolates business logic from ORM dependencies and avoids unexpected lazy-loading database queries outside active sessions.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.