Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Typed Models and Relationships

Translate the reading-list schema into typed SQLAlchemy 2.x models with constraints and a one-to-many relationship, create the tables and watch the database enforce the rules.

Contentsand lesson path

What you will learn

  • Declare typed ORM models with relationships and constraints that match a relational schema.

Prerequisites: SQL Fundamentals

01. The task

The reading list has a schema: authors, each with a name that identifies them, and books that belong to exactly one author. You designed tables like these in relational data modelling — keys, constraints and all. This worked example translates that schema into typed Python models with SQLAlchemy 2.x, creates the tables in PostgreSQL, and proves the constraints hold.

A model class does three jobs at once. It is DDL: SQLAlchemy can create the table from the class. It is a query building block: select(Author) and Author.name come from the class. And it is a type: instances are annotated Python objects your editor can check. The mapping is deliberately thin — the modelling happened before it, and the model must match the schema, not invent one.

The lab database is the throwaway PostgreSQL 17 container from the first SQL lesson, on port 55433. The driver is psycopg 3, written postgresql+psycopg:// in the URL.

02. Step 1: declare the models

In 2.x, a class with __tablename__ inherits from a DeclarativeBase, and every column is a Mapped annotation paired with mapped_column. The annotation is not decoration: a plain type such as Mapped[str] makes the column NOT NULL, Mapped[str | None] makes it nullable, and Mapped[int] on a primary key becomes an auto-incrementing integer. Python type checkers see real types, and the database sees matching constraints.

Python · models.py
from datetime import datetime

from sqlalchemy import (
    CheckConstraint,
    ForeignKey,
    String,
    UniqueConstraint,
    func,
)
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100), unique=True)

    books: Mapped[list["Book"]] = relationship(
        back_populates="author",
        cascade="all, delete-orphan",
    )


class Book(Base):
    __tablename__ = "books"
    __table_args__ = (
        UniqueConstraint("author_id", "title", name="uq_books_author_title"),
        CheckConstraint("pages >= 0", name="ck_books_pages"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(
        ForeignKey("authors.id", ondelete="CASCADE"), index=True
    )
    title: Mapped[str] = mapped_column(String(200))
    subtitle: Mapped[str | None]
    pages: Mapped[int]
    created_at: Mapped[datetime] = mapped_column(server_default=func.now())

    author: Mapped["Author"] = relationship(back_populates="books")

Read Book against what the schema demands. author_id carries the ForeignKey to authors.id — that is the one-to-many link, and ondelete="CASCADE" states what the database does when an author row disappears. The __table_args__ tuple holds the rules a single column cannot express: one book title per author, and page counts that cannot go negative. created_at uses server_default=func.now(), so PostgreSQL stamps the time when it inserts the row rather than Python stamping it earlier.

The two relationship() declarations are one relationship seen from both ends: author.books is a list of Book, book.author is one Author, and back_populates keeps the pair in step. A relationship never replaces a column — it is navigation on top of the foreign key, and SQLAlchemy finds the join condition from that key.

03. Step 2: see the SQL the models produce

Before touching the database, ask SQLAlchemy what it would run. Compiling CreateTable for the PostgreSQL dialect prints the DDL — this is the fastest way to check that the class and the schema agree, and it needs no connection. Import it from sqlalchemy.schema, which works on every 2.x release (the shorter from sqlalchemy import CreateTable only exists from 2.1).

Python · show the DDL for books
from sqlalchemy.schema import CreateTable
from sqlalchemy.dialects import postgresql

from models import Book

print(
    CreateTable(Book.__table__).compile(dialect=postgresql.dialect())
)
Expected output

CREATE TABLE books (
	id SERIAL NOT NULL, 
	author_id INTEGER NOT NULL, 
	title VARCHAR(200) NOT NULL, 
	subtitle VARCHAR, 
	pages INTEGER NOT NULL, 
	created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL, 
	PRIMARY KEY (id), 
	CONSTRAINT uq_books_author_title UNIQUE (author_id, title), 
	CONSTRAINT ck_books_pages CHECK (pages >= 0), 
	FOREIGN KEY(author_id) REFERENCES authors (id) ON DELETE CASCADE
)

Every annotation landed where it should: SERIAL for the auto-incrementing primary key, NOT NULL where the annotation was plain, plain VARCHAR for the nullable subtitle, and both constraints under the names you gave them. Base.metadata.create_all(engine) runs this DDL for real. It is perfect for a lab or a test database; a production service manages its schema with versioned migrations instead, which the schema migrations skill covers.

04. Step 3: create rows through the relationship

With the tables created, seed them the way application code writes data: build objects, link them through the relationship, and let one commit flush the lot as a single transaction.

Python · seed.py (abridged)
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session

from models import Author, Base, Book

engine = create_engine(
    "postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

le_guin = Author(
    name="Ursula K. Le Guin",
    books=[
        Book(title="The Left Hand of Darkness", pages=304),
        Book(title="The Dispossessed", subtitle="An Ambiguous Utopia", pages=346),
    ],
)
herbert = Author(name="Frank Herbert", books=[Book(title="Dune", pages=412)])

with Session(engine) as session:
    session.add_all([le_guin, herbert])
    session.commit()

    for author in session.scalars(select(Author).order_by(Author.name)):
        print(author.name, "->", [b.title for b in author.books])
Expected output
Frank Herbert -> ['Dune']
Ursula K. Le Guin -> ['The Left Hand of Darkness', 'The Dispossessed']

You never set author_id by hand. Appending Book objects to author.books is the same fact as setting book.author, because back_populates mirrors the two sides; at flush time SQLAlchemy writes the parents first, copies the generated ids into author_id, and inserts the children. Both inserts and the ordering come from one commit(), so a failure anywhere leaves the database as it was.

The cascade="all, delete-orphan" option extends the same idea to removal: delete an author from the session and the ORM deletes that author's books in the same transaction, matching the ON DELETE CASCADE on the foreign key. The two settings live at different layers — one tells the ORM what to do with Python objects, the other tells PostgreSQL what to do with rows — and a service that only ever deletes through the ORM will notice neither. Keeping both means the rule holds whichever path removes a row, including a manual DELETE run in psql during an incident.

05. Step 4: let the database say no

Try to give Frank Herbert a second book called Dune. Python has no objection; PostgreSQL does.

Python · violate the unique constraint
from sqlalchemy.exc import IntegrityError

with Session(engine) as session:
    author = session.scalars(
        select(Author).where(Author.name == "Frank Herbert")
    ).one()
    session.add(Book(title="Dune", pages=196, author_id=author.id))
    try:
        session.commit()
    except IntegrityError as err:
        session.rollback()
        print(
            "IntegrityError:",
            type(err.orig).__name__,
            "on",
            err.orig.diag.constraint_name,
        )
Expected output
IntegrityError: UniqueViolation on uq_books_author_title

The constraint you named in __table_args__ is the one PostgreSQL reports, and the exception arrives only at commit() — the point where the work is flushed. This is why rules live in the schema and not only in a service check: two requests can run the same "does it exist yet?" question at the same moment and both answer no, and only the database sees the collision. Catch the error, roll the session back, and let the caller decide what to tell the user.

06. Check your understanding

Practice check · 3 questions

Models, relationships, constraints

Reason about the mapping you just built.

Q1. With back_populates set on both sides, what does author.books.append(book) do in the seeded session?
Q2. You delete an Author object from the session and commit. What happens to its books under cascade="all, delete-orphan"?
Q3. created_at is declared with server_default=func.now(). Where does its value come from?
Practice only: not graded, not saved, not evidence.

07. Apply it

Extend models.py for this skill's practice. Add a reading_status column to Book limited to the values unopened, reading and finished — as a CheckConstraint, not a Python enum check. Add a UniqueConstraint you can justify in one sentence, and an index=True where a query from the practice (listing an author's books) would need it. Recreate the tables and recompile the DDL: every new rule should appear in the output, named.

08. Review prompt

Without looking back: how does the Mapped annotation decide whether a column is nullable? What two things must exist for a relationship() to be configured, and what does back_populates add? Where do you state a rule that spans two columns, and when is it checked? And what is the difference between cascade="all, delete-orphan" and ondelete="CASCADE" — which layer runs each?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check