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
- SQLAlchemy Core vs ORM
- Defining Models
- Querying with the Session
- Relationships and Joins