Skip to content

Grouped result of multiple joins #118

Description

@terencetwuo

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

def get_model_detail(session: Session, id: int):
    data = session.query(ModelProfile, SubModelProfile).join(SubModelProfile, ModelProfile.id  == SubModelProfile.mp_id).filter(ModelProfile.id == id).all()

    return data

Description

  • Above code is trying to retrieve one-to-many relationship of ModelProfile [1:M] SubModelProfile
  • It results in duplicate ModelProfile in the result:
[
  {
    "ModelProfile": {
      "model_version": "1",
      "id": 1,
      "created_at": "2021-09-15T14:01:52"
    },
    "SubModelProfile": {
      "mp_id": 1,
      "id": 1
    }
  },
  {
    "ModelProfile": {
      "model_version": "1",
      "id": 1,
      "created_at": "2021-09-15T14:01:52"
    },
    "SubModelProfile": {
      "mp_id": 1,
      "id": 2
    }
  },
  {
    "ModelProfile": {
      "model_version": "1",
      "id": 1,
      "created_at": "2021-09-15T14:01:52"
    },
    "SubModelProfile": {
      "mp_id": 1,
      "id": 3
    }
  }
]

Question: I'm expecting the result to look like:

[
  {
    "ModelProfile": {
      "model_version": "1",
      "id": 1,
      "created_at": "2021-09-15T14:01:52"
    },
    "SubModelProfile": [
       {
        "mp_id": 1,
        "id": 1
      }, {
       "mp_id": 1,
       "id": 2
      }, {
      "mp_id": 1,
      "id": 3
      }
   ]
  }
]

Or this (what I wish to achieve)

[
  {
    "model_profile": {
      "model_version": "1",
      "id": 1,
      "created_at": "2021-09-15T14:01:52"
      "sub_model_profiles":  [
           {
            "mp_id": 1,
            "id": 1
          }, {
           "mp_id": 1,
           "id": 2
          }, {
          "mp_id": 1,
          "id": 3
          }
      ]
  }
]

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

3.7.11

Additional Context

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions