skip to content

In SQLAlchemy, when do you map Post-to-Tag through relationship(secondary=post_tags), and when through an association-object class instead?

level: middleimportance: should knowfreq 42%

answer

  1. does the link row hold data?
  2. a Table versus a mapped class
  3. who writes the link rows
  4. the proxy that hides the hop

basics

~20 s

Use secondary= when post_tags holds only the two foreign keys: SQLAlchemy inserts and deletes link rows as tags are added or removed. Once the link row carries data, map post_tags to its own class and reach tags through it.

solid answer

~40 s

`relationship(secondary=post_tags)` takes a Core `Table` and manages it entirely: appending a tag to `post.tags` inserts a link row and removing one deletes it, with no class for the link. The relationship supplies only the two keys for that INSERT, so when `post_tags` gains a column with a per-link value such as `tagged_by`, map it as an **association object**: a `PostTag` class with a composite primary key, `Post.post_tags` as a one-to-many to it and `PostTag.tag` as a many-to-one to `Tag`. Links are then created as `PostTag(tag=..., tagged_by=...)`, and `association_proxy` can restore a direct `post.tags` view. Do not leave a writable `secondary=` relationship on the same table: SQLAlchemy warns that both write the same columns, and mixed writes produce duplicate or incomplete rows, so mark it `viewonly=True` if you keep it.

code

python · 50 lines
python
from __future__ import annotations

from sqlalchemy import ForeignKey, String, create_engine, select
from sqlalchemy.ext.associationproxy import AssociationProxy, association_proxy
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class PostTag(Base):
    __tablename__ = "post_tags"
    post_id: Mapped[int] = mapped_column(ForeignKey("posts.id"), primary_key=True)
    tag_id: Mapped[int] = mapped_column(ForeignKey("tags.id"), primary_key=True)
    tagged_by: Mapped[str] = mapped_column(String(50))
    post: Mapped[Post] = relationship(back_populates="post_tags")
    tag: Mapped[Tag] = relationship()


class Post(Base):
    __tablename__ = "posts"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(200))
    post_tags: Mapped[list[PostTag]] = relationship(
        back_populates="post", cascade="all, delete-orphan"
    )
    # read-only shortcut through the association rows
    tags: AssociationProxy[list[Tag]] = association_proxy("post_tags", "tag")


class Tag(Base):
    __tablename__ = "tags"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(50), unique=True)


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

with Session(engine) as session, session.begin():
    python = Tag(name="python")
    post = Post(title="Cascades in practice")
    post.post_tags.append(PostTag(tag=python, tagged_by="editor"))
    session.add(post)

with Session(engine) as session:
    post = session.scalars(select(Post)).one()
    print([t.name for t in post.tags])
    print([(pt.tag.name, pt.tagged_by) for pt in post.post_tags])

go deeper

for a junior

Recall that secondary= points relationship() at a plain link Table and that SQLAlchemy writes the link rows when you append to or remove from the collection.

for a middle

Explain the switch to an association class once the link row carries data, the four relationships it needs for both directions, and what association_proxy adds.

for a senior

Spot the trap of a writable secondary= left beside the association class: conflicting writes, extra columns left unset and duplicate inserts, fixed with viewonly=True.

for a principal

Decide early whether a link may ever carry data; starting with an association class costs a little verbosity but avoids remapping a busy relationship later.

## Plain many-to-many: relationship(secondary=...) When the link between posts and tags is nothing more than a pair of keys, the link table stays a Core `Table` and never becomes a class. It is declared on the base's `MetaData`, with `Column` (not `mapped_column()`) and a composite primary key so a post cannot be tagged twice: ```python post_tags = Table( "post_tags", Base.metadata, Column("post_id", ForeignKey("posts.id"), primary_key=True), Column("tag_id", ForeignKey("tags.id"), primary_key=True), ) class Post(Base): __tablename__ = "posts" id: Mapped[int] = mapped_column(primary_key=True) tags: Mapped[list[Tag]] = relationship(secondary=post_tags, back_populates="posts") ``` `Tag.posts` mirrors it with the same `secondary=` and `back_populates="tags"`. `secondary=` also accepts the table name as a string, or a lambda, when the table is defined later. ## What SQLAlchemy writes for you The defining trait of `secondary=` is that the link table is **managed by the relationship**. There is no need to insert into or delete from `post_tags` yourself: 1. `post.tags.append(tag)` makes the flush emit an `INSERT INTO post_tags` with both keys. 2. `post.tags.remove(tag)` makes it emit `DELETE FROM post_tags WHERE post_tags.post_id = ? AND post_tags.tag_id = ?`. The tag row itself stays. 3. `session.delete(tag)` removes the tag's link rows only if some `relationship()` on `Tag` (here `Tag.posts`) lets SQLAlchemy find them; it loads that collection to do so. With no relationship from the deleted side, no link rows are deleted, and an enforced foreign key then rejects the tag's DELETE. 4. `ON DELETE CASCADE` on the two link-table foreign keys plus `passive_deletes=True` lets the database clear link rows without that load. Deleting a post follows the same rule, and cascade settings change how far it reaches: - `session.delete(post)` deletes the post's `post_tags` rows and leaves every tag in place. - `cascade="all, delete"` on `Post.tags` would delete the tags themselves as well, which is rarely right for tags shared by many posts. - The same `delete` cascade on **both** `Post.tags` and `Tag.posts` walks from posts to tags to posts and deletes everything connected; the documentation warns against configuring it in both directions. ## When the link row carries data: the association object As soon as `post_tags` holds more than the two keys, such as who added the tag, `secondary=` can no longer write it correctly: the relationship supplies values only for `post_id` and `tag_id`. An extra column gets its `Column` default if it has one and `NULL` otherwise, and a `NOT NULL` extra column with no default turns the flush into an `IntegrityError`. There is no way to pass a per-link value such as the editor's name through `post.tags.append()`. The **association object** pattern maps the link table to its own class and drops `secondary=`: - `PostTag` maps `post_tags`, with `post_id` and `tag_id` as a composite primary key and `tagged_by` as an ordinary column. - `Post.post_tags` is a one-to-many to `PostTag`, usually with `cascade="all, delete-orphan"` so removing a link deletes its row. - `PostTag.tag` is a many-to-one to `Tag`; a bidirectional mapping adds `PostTag.post` and `Tag.post_tags`, four relationships in all. - Code creates the link explicitly: `post.post_tags.append(PostTag(tag=python, tagged_by="editor"))`. ## Getting direct access back Going through `PostTag` for every read is verbose. The `sqlalchemy.ext.associationproxy` extension adds an attribute that hops across the association class: ```python tags: AssociationProxy[list[Tag]] = association_proxy("post_tags", "tag") ``` `post.tags` then reads like a list of `Tag` objects, while the rows are still `PostTag` rows. Appending a `Tag` through the proxy calls `PostTag(tag)` with one positional argument, which the default Declarative constructor (keyword arguments only) rejects, so pass a `creator=` callable such as `lambda tag: PostTag(tag=tag, tagged_by=...)`; that callable is also where a value such as `tagged_by` has to come from. ## Do not keep a writable secondary= next to the class The tempting shortcut is to keep `Post.tags = relationship(secondary="post_tags")` beside the new `PostTag` mapping. The two now write the same columns without knowing about each other: - Mapper configuration emits `SAWarning: relationship 'Post.tags' will copy column posts.id to column post_tags.post_id, which conflicts with relationship(s): ...`. - Changes through one path are invisible to the other until the `Session` is expired. - Appending the same tag through both paths flushes two INSERTs for one primary key, and appending through `Post.tags` never sets `tagged_by` itself. If the shortcut is worth keeping for reads, mark it `viewonly=True`, which stops it writing at all. `overlaps=` only silences the warning and leaves both writers in place. | | `secondary=` | association object | |---|---|---| | Link table mapped as | a Core `Table` | its own class | | Extra columns | not written | ordinary mapped attributes | | Link rows created by | appending to the collection | constructing the association class | | Access to the other side | `post.tags` directly | `post.post_tags[i].tag`, or an association proxy |

  • With secondary=, why might deleting a Tag leave rows behind in post_tags?
    SQLAlchemy clears link rows for a deleted object only by following a relationship() from that object's class. If only Post.tags exists, nothing on Tag points at post_tags, so session.delete(tag) leaves its link rows and an enforced foreign key rejects the delete. Add Tag.posts, or put ON DELETE CASCADE on the link-table keys with passive_deletes=True.
  • What does an association proxy need before code can append a Tag through it?
    A `creator=` callable on `association_proxy()`, or a PostTag constructor that takes one positional argument. By default the proxy calls `PostTag(tag)`, and the default Declarative constructor accepts keyword arguments only. The creator, such as `lambda tag: PostTag(tag=tag, tagged_by=...)`, is also where a required column such as tagged_by gets its value.

  • With secondary= you must insert and delete post_tags rows yourself.
  • post.tags.append(tag) can also set tagged_by on the new link row.
  • Keeping secondary= and an association class writable on one table is harmless.
  • overlaps= on the secondary relationship stops it writing to the link table.
  • Removing a tag from post.tags deletes the tag row itself.