First Check
Commit to Help
Example Code
fromtypingimportList, OptionalfromfastapiimportDepends, FastAPI, HTTPException, QueryfromsqlmodelimportField, Relationship, Session, SQLModel, create_engine, selectclassTeamBase(SQLModel):
name: strheadquarters: strclassTeam(TeamBase, table=True):
id: Optional[int] =Field(default=None, primary_key=True)
heroes: List["Hero"] =Relationship(back_populates="team")
classTeamCreate(TeamBase):
passclassTeamRead(TeamBase):
id: intclassTeamUpdate(SQLModel):
id: Optional[int] =Nonename: Optional[str] =Noneheadquarters: Optional[str] =NoneclassHeroBase(SQLModel):
name: strsecret_name: strage: Optional[int] =Noneteam_id: Optional[int] =Field(default=None, foreign_key="team.id")
classHero(HeroBase, table=True):
id: Optional[int] =Field(default=None, primary_key=True)
team: Optional[Team] =Relationship(back_populates="heroes")
classHeroRead(HeroBase):
id: intclassHeroCreate(HeroBase):
passclassHeroUpdate(SQLModel):
name: Optional[str] =Nonesecret_name: Optional[str] =Noneage: Optional[int] =Noneteam_id: Optional[int] =NoneclassHeroReadWithTeam(HeroRead):
team: Optional[TeamRead] =NoneclassTeamReadWithHeroes(TeamRead):
heroes: List[HeroRead] = []
sqlite_file_name="database.db"sqlite_url=f"sqlite:///{sqlite_file_name}"connect_args= {"check_same_thread": False}
engine=create_engine(sqlite_url, echo=True, connect_args=connect_args)
defcreate_db_and_tables():
SQLModel.metadata.create_all(engine)
defget_session():
withSession(engine) assession:
yieldsessionapp=FastAPI()
@app.on_event("startup")defon_startup():
create_db_and_tables()
@app.post("/heroes/", response_model=HeroRead)defcreate_hero(*, session: Session=Depends(get_session), hero: HeroCreate):
db_hero=Hero.from_orm(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
returndb_hero@app.get("/heroes/", response_model=List[HeroRead])defread_heroes(
*,
session: Session=Depends(get_session),
offset: int=0,
limit: int=Query(default=100, lte=100),
):
heroes=session.exec(select(Hero).offset(offset).limit(limit)).all()
returnheroes@app.get("/heroes/{hero_id}", response_model=HeroReadWithTeam)defread_hero(*, session: Session=Depends(get_session), hero_id: int):
hero=session.get(Hero, hero_id)
ifnothero:
raiseHTTPException(status_code=404, detail="Hero not found")
returnhero@app.patch("/heroes/{hero_id}", response_model=HeroRead)defupdate_hero(
*, session: Session=Depends(get_session), hero_id: int, hero: HeroUpdate
):
db_hero=session.get(Hero, hero_id)
ifnotdb_hero:
raiseHTTPException(status_code=404, detail="Hero not found")
hero_data=hero.dict(exclude_unset=True)
forkey, valueinhero_data.items():
setattr(db_hero, key, value)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
returndb_hero@app.delete("/heroes/{hero_id}")defdelete_hero(*, session: Session=Depends(get_session), hero_id: int):
hero=session.get(Hero, hero_id)
ifnothero:
raiseHTTPException(status_code=404, detail="Hero not found")
session.delete(hero)
session.commit()
return {"ok": True}
@app.post("/teams/", response_model=TeamRead)defcreate_team(*, session: Session=Depends(get_session), team: TeamCreate):
db_team=Team.from_orm(team)
session.add(db_team)
session.commit()
session.refresh(db_team)
returndb_team@app.get("/teams/", response_model=List[TeamRead])defread_teams(
*,
session: Session=Depends(get_session),
offset: int=0,
limit: int=Query(default=100, lte=100),
):
teams=session.exec(select(Team).offset(offset).limit(limit)).all()
returnteams@app.get("/teams/{team_id}", response_model=TeamReadWithHeroes)defread_team(*, team_id: int, session: Session=Depends(get_session)):
team=session.get(Team, team_id)
ifnotteam:
raiseHTTPException(status_code=404, detail="Team not found")
returnteam@app.patch("/teams/{team_id}", response_model=TeamRead)defupdate_team(
*,
session: Session=Depends(get_session),
team_id: int,
team: TeamUpdate,
):
db_team=session.get(Team, team_id)
ifnotdb_team:
raiseHTTPException(status_code=404, detail="Team not found")
team_data=team.dict(exclude_unset=True)
forkey, valueinteam_data.items():
setattr(db_team, key, value)
session.add(db_team)
session.commit()
session.refresh(db_team)
returndb_team@app.delete("/teams/{team_id}")defdelete_team(*, session: Session=Depends(get_session), team_id: int):
team=session.get(Team, team_id)
ifnotteam:
raiseHTTPException(status_code=404, detail="Team not found")
session.delete(team)
session.commit()
return {"ok": True}Description
Is realationships working for anyone?
I either get null or an empty list.
OK, so, I've copied the last full file preview at the - https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/
Run it and it creates the Db and the foreign key
Then I've insert the data into the Db.
Checking the docs UI everything looks great

But when I do a request for a hero, team is null

Really not sure what going on, especially when all I have just is copied the code example with no changes?
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
3.8.2
Additional Context
No response
First Check
Commit to Help
Example Code
Description
Is realationships working for anyone?
I either get null or an empty list.
OK, so, I've copied the last full file preview at the - https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/
Run it and it creates the Db and the foreign key
Then I've insert the data into the Db.
Checking the docs UI everything looks great

But when I do a request for a hero,

teamisnullReally not sure what going on, especially when all I have just is copied the code example with no changes?
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
3.8.2
Additional Context
No response