Skip to content

Grouped result of multiple joins #1512

Discussion options

You must be logged in to vote

You can specify relationships between these models:

class ModelProfile(ModelProfileBase, table=True):
    ...
    sub_model_profiles: list["SubModelProfile"] = Relationship(back_populates="model_profile")

class SubModelProfile(SQLModel, table=True):
    ...
    mp_id: int = Field(foreign_key="modelprofile.id")
    model_profile: ModelProfile = Relationship(back_populates="sub_model_profiles")

And then fetch it just like this:

mp1_db = session.get(ModelProfile, 1)

or with select and eager loading:

        mp1_db = session.exec(
            select(ModelProfile)
            .where(ModelProfile.id == 1)
            .options(selectinload(ModelProfile.sub_model_profiles))
        ).one()

Runna…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
4 participants
Converted from issue

This discussion was converted from issue #118 on August 13, 2025 09:58.