i'm using django-mptt for a hierarchical model in my app. i've created a nested serializer for it, but it does not take advantage of MPTT's query efficiency. It's instead simply using recursive queries. i'd like to know if there's a way to make that optimization.
First a little background for those unfamiliar with MPTT: django-mptt allows me to return an entire hierarchical tree in a single query, by ordering all the objects from "left to right" and returning their level (depth in tree) and parent. For example, i have top-level object A which has three children: B, C, and D. C has two children, E and F. Myobject.objects.get_descendants(include_self=True) will return a queryset looking something like this: [<A level=0>, <B level=1>, <C level=1>, <E level=2>, <F level=2>, <D level=1>] (each node has a 'parent' explicitly defined, as well).
The order of the queryset, along with the "level" information, is enough to draw out the tree structure. For example:
>>> objectA = MyModel.objects.toplevel().first() # get a root node
>>> for node in objectA.get_descendants(include_self=True):
... print '%s%s' % (node.level * '--', node)
...
Object A
--Object B
--Object C
----Object E
----Object F
--Object D
You can imagine what it might look like as a nested JSON object.
So my question is, how might i approach writing a nested model serializer that would work the same way, which would require a single query rather than three recursive queries? Has anyone already solved this?