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.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
I'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 System
Linux
Operating System Details
No response
SQLModel Version
0.0.14
Python Version
3.10
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions