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
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.
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.
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.