nested model serializer for django-mptt

703 views
Skip to first unread message

smcoll

unread,
Oct 24, 2014, 11:24:43 AM10/24/14
to django-res...@googlegroups.com
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?

Rukaya Johaadien

unread,
Sep 12, 2016, 9:49:25 AM9/12/16
to Django REST framework
Hi Smcoll, I'd be really interested in knowing what you did in the end to solve this. 

Shannon Collins

unread,
Sep 14, 2016, 12:30:09 PM9/14/16
to Django REST framework
Unfortunately, we never made this optimization.  The project underwent a pretty significant change and we stopped using MPTT.

--
You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/5yS0U6J9iUg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages