0Pricing
Python Academy · Lesson

Relationships and Joins

Model related tables.

Related Tables

Real data is connected: an author has many books, an order has many items. SQLAlchemy models these links with relationships and foreign keys.

# Author 1 --- many --- Book
# A foreign key on Book points back to Author
print('One-to-many is the most common link')

Foreign Keys

A foreign key column stores the primary key of a related row. Declare it with ForeignKey('table.column').

from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
# author_id: Mapped[int] = mapped_column(ForeignKey('authors.id'))
print('ForeignKey links child to parent')

All lessons in this course

  1. SQLAlchemy Core vs ORM
  2. Defining Models
  3. Querying with the Session
  4. Relationships and Joins
← Back to Python Academy