Skip to content

Bi-directional one to many relationship #124

Closed
@petercinibulk

Description

@petercinibulk

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import List, Optional

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


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

    heroes: List["Hero"] = Relationship(back_populates="team")


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

    team_id: Optional[int] = Field(default=None, foreign_key="team.id")
    team: Optional[Team] = Relationship(back_populates="heroes")

Description

When I create a one to many relationship such as the example code which I got from the docs, the team_id is auto populated with the id of the team when I add a team to a hero.

I want the reverse to happen. I want to be able to have a field on the Team class that contains a List of the hero ids. I know there is a way to get all of the heroes as mentioned here (https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/), but for this scenario, I only want a List of the ids of the Heros.

I know the below code doesn't work but it would be nice to do something like it and have the ids automatically be there.

class Team(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    headquarters: str
    hero_ids: Optional[List[int]] = Field(default=None, foreign_key="hero.id")  // New
    heroes: List["Hero"] = Relationship(back_populates="team")

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

Python 3.8.6

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions