I have 3 models that look like this (simplified):
User:
id
username
Resource:
id
name
description
Comment:
id
user_id (relationship User)
resource_id (relationship Resource)
data
date_created
I am trying to query the comments for a user and group them by Resource. I'd like the results to come back as: [(Resource A, [Comment, Comment, Comment, ...]), (Resource B, [Comment, Comment, ...]), (Resource X, [Comment])]
I have tried various ways of constructing this and I just can't seem to figure it out. What would be the proper way to do something like this?
EDIT
Right now the code looks like this:
contrib = db_session.query(Resource).filter(Comment.user==user, Resource.uuid==Comment.resource_id).distinct(Comment.resource_id).order_by(desc(Comment.date_created))
comments = db_session.query(Comment, Resource).filter(Comment.user==user, Comment.resource_id.in_([r.uuid for r in contrib]), Resource.uuid==Comment.resource_id).order_by(desc(Comment.date_created))
I then use some list/dictionary comprehension to combine these results into something that looks like
[{resource: Resource, comments:[Comment, Comment, Comment]}, {resource: Resource, comments:[Comment, .....]}, .....]
There has got to be a better way to do this!