-
First Check
Commit to Help
Example Code@app.get("/teams/{team_id}", response_model=TeamReadWithHeroes)
def read_team(*, team_id: int, include_heroes: bool = False, session: Session = Depends(get_session)):
team = session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")
return team DescriptionI've recently begun working with SQLModel in conjunction with FastAPI and have encountered a challenge regarding conditional loading of related entities. Following the official documentation on Models with Relationships, it appears that the TeamReadWithHeroes model automatically includes the "heroes" relationship. However, I am looking to make the inclusion of "heroes" optional, based on a URL parameter (e.g., "include_heroes=true"). My initial thought was to leverage Pydantic's model_validate along with some context or a discriminator to achieve this. The ideal solution would allow for disabling lazy loading on the relationship unless explicitly joined, providing a default return if the relationship is not included. Does anyone have a simpler approach or solution to selectively load related entities based on a URL parameter with SQLModel and FastAPI? Related link:
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.14 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
For now, I opted for the following solution: TeamResponse = Union[TeamRead, TeamReadWithHeroes]
@app.get("/teams/{team_id}", response_model=TeamResponse)
def read_team(*, team_id: int, include_heroes: bool = False, session: Session = Depends(get_session)):
model_class = TeamRead
if include_heroes:
model_class = TeamReadWithHeroes
team = session.get(Team, team_id)
if not team:
raise HTTPException(status_code=404, detail="Team not found")
return model_class.model_validate(team) |
Beta Was this translation helpful? Give feedback.
For now, I opted for the following solution: