First Check
Commit to Help
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
First Check
Commit to Help
Example Code
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.
Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
Python 3.8.6
Additional Context
No response