ChildForum = aliased(Forum)
q = query(Forum, ChildForum, func.count(Message.id)).filter(Forum.parent ==
    None).outerjoin((ChildForum, Forum.children)).outerjoin(ChildForum.posts
    ).group_by(Forum, ChildForum)
from itertools import groupby
from operator import attrgetter
for forum, childforums in groupby(q, key=attrgetter('Node')):
    for _, child, post_count in childforums:
        if child is None:
            break
Как вернуть количество связанных сущностей в запросе sqlalchemy