Note

This post is a thought. It's a short note that I make about someone else's content online. Learn more about the process thoughts

Here's my thought on ๐Ÿ’ญ Create Models with a Many-to-Many Link - SQLModel


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.

many-to-many relationship model


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)

This post was a thought by Waylon Walker see all my thoughts at https://waylonwalker.com/thoughts