---
title: "💭 Create Models with a Many-to-Many Link - SQLModel"
description: "!https://sqlmodel.tiangolo.com/tutorial/many-to-many/create-models-with-link/"
date: 2023-08-09
published: true
tags:
  - python
  - api
  - fastapi
  - thought
template: link
---


<div class="embed-card embed-card-external">
  <a href="https://sqlmodel.tiangolo.com/tutorial/many-to-many/create-models-with-link/" class="embed-card-link" target="_blank" rel="noopener noreferrer">
    <div class="embed-card-image">
      <img src="https://sqlmodel.tiangolo.com/assets/images/social/tutorial/many-to-many/create-models-with-link.png" alt="Create Models with a Many-to-Many Link - SQLModel — SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness." loading="lazy">
    </div>
    <div class="embed-card-content">
      <div class="embed-card-title">Create Models with a Many-to-Many Link - SQLModel</div>
      <div class="embed-card-description">SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.</div>
      <div class="embed-card-meta">sqlmodel.tiangolo.com</div>
    </div>
  </a>
</div>


Creating many to many relationships with sqlmodel requires a LinkTable Model.  The link model will keep track of the linked id's between each of the models.

<img src="https://sqlmodel.tiangolo.com/img/tutorial/many-to-many/many-to-many.svg" alt="many-to-many relationship model" style="
    width: 100%;
">

``` python
from typing import List, Optional

from sqlmodel import Field, Relationship, Session, SQLModel, create_engine


class HeroTeamLink(SQLModel, table=True):
    team_id: Optional[int] = Field(
        default=None, foreign_key="team.id", primary_key=True
    )
    hero_id: Optional[int] = Field(
        default=None, foreign_key="hero.id", primary_key=True
    )


class Team(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    headquarters: str

    heroes: List["Hero"] = Relationship(back_populates="teams", link_model=HeroTeamLink)


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    secret_name: str
    age: Optional[int] = Field(default=None, index=True)

    teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
```

!!! note

    This post is a <a href="/thoughts/" class="wikilink" data-title="Thoughts" data-description="These are generally my thoughts on a web page or some sort of url, except a rare few don&#39;t have a link. These are dual published off of my..." data-date="2024-04-01">thought</a>. It's a short note that I make
    about someone else's content online <a href="/tags/thoughts/" class="hashtag-tag" data-tag="thoughts" data-count=2 data-reading-time=3 data-reading-time-text="3 minutes">#thoughts</a>
