typestar

Relationships in Python

A foreign key plus relationship gives you objects on both sides.

from sqlalchemy import ForeignKey, create_engine
from sqlalchemy.orm import (DeclarativeBase, Mapped, Session, mapped_column,
                            relationship)


class Base(DeclarativeBase):
    pass


class Tour(Base):
    __tablename__ = "tours"
    id: Mapped[int] = mapped_column(primary_key=True)
    slug: Mapped[str]
    steps: Mapped[list["Step"]] = relationship(back_populates="tour")


class Step(Base):
    __tablename__ = "steps"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    tour_id: Mapped[int] = mapped_column(ForeignKey("tours.id"))
    tour: Mapped[Tour] = relationship(back_populates="steps")


engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)

with Session(engine) as session:
    tour = Tour(slug="basics")
    tour.steps = [Step(title="Variables"), Step(title="Strings")]
    session.add(tour)
    session.commit()
    print(len(tour.steps), tour.steps[0].tour.slug)

How it works

  1. ForeignKey is the column; relationship is the attribute.
  2. back_populates keeps the two sides in step.
  3. Appending to the collection sets the key for you.

Keywords and builtins used here

The run, in numbers

Lines
33
Characters to type
880
Tokens
228
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 124 seconds.

Type this snippet

Step 5 of 5 in SQLAlchemy, step 17 of 19 in Web services & data access.

← Previous Next →