sqlalchemy aggregate results into one

Viewed 31

I have a little problem with modifying an SQLALchemy query to the way I need.

The current query -

data = db.query(Person.id, Worker.worker_name, User.username)
            .filter(Person.id == Worker.person_id) \
            .filter(Worker.id == User.worker_id) \
            .all()

return the below response

Response
[
  {
    "id": "d258f5d6-98ba-4e03-920d-38bd139fbf65",
    "worker_name": "Josh",
    "username": "some-user"
  },
  {
    "id": "d258f5d6-98ba-4e03-920d-38bd139fbf65",
    "worker_name": "Josh,
    "username": "good-user"
  },
  {
  {
    "id": "416981b5-7ba0-4d1e-9574-a6bef8bbc102",
    "worker_name": "Jenne",
    "username": "random-user"
  },
  {
    "id": "416981b5-7ba0-4d1e-9574-a6bef8bbc102",
    "worker_name": "Jenne",
    "username": "bad-user"
  },
  {
    "id": "416981b5-7ba0-4d1e-9574-a6bef8bbc102",
    "worker_name": "Jenne",
    "username": "ok-user"
  }
]

The response contains the data I need, but I want to output with a query this kind of response -

which combines different usernames under the same worker_name or id.

[
  {
    "id": "d258f5d6-98ba-4e03-920d-38bd139fbf65",
    "worker_name": "Josh",
    "username": ["some-user", "good-user]
  },
  {
    "id": "416981b5-7ba0-4d1e-9574-a6bef8bbc102",
    "worker_name": "Jack",
    "username": ["random-user", "bad-user", "ok-user"]
  }
]
0 Answers
Related