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
How to return the count of related entities in sqlalchemy query