Group by the parent in NDB query

Uri Source

Say I've a model with School, Class, Student models. In this model, classes are children of School, and students are children of class. What I'd like is to get all the students, grouped by their class.

Using NDB I can get call students for school A with:

school_key = ndb.Key( 'School', 'A' )
all_students_in_A = Student.query( ancestor = school_key ).fetch( )

However, I'd like to get the students in A groups by their class. Looking at the doc, query accepts a group_by argument, but only for actual fields of a model.

google-app-engineapp-engine-ndb

Answers

answered 5 years ago Daniel Roseman #1

I would do the grouping in Python after fetching the students.

classes = defaultdict(list)
for student in all_students_in_A:
    class = student.key.id()
    classes[class].append(student)

Now classes is a dict, where the keys are the class IDs and the values are lists of students.

answered 5 years ago Tim Hoffman #2

I have been using the python groupby function from itertools to post process and group entities.

Your selection needs to sort in the required order, in your case by key as your parents are in the key.

This approach will maintain the order.

http://docs.python.org/2/library/itertools.html#itertools.groupby

The code I have got is not easily shareable as the grouping function I have is part of a stored/authorable query entity which allows grouping by multiple attributes of the result items and the implementation is spread across a number of methods. But shout out if you would like to see some code.

comments powered by Disqus