I'm using Django-MPTT to do a display a simple 2 level hierarchy (root => child(ren)). I'm looking for a way to structure my queryset so that nodes get returned with the root node having the most children first and the node with the least children (if any) last.
Asked
Active
Viewed 1,920 times
2 Answers
4
Take a look at your parent
field and make note of the related_name. Suppose it is children
. Then do the following:
from django.db.models import Count
MyMPTTModel.objects.root_nodes().annotate(
Count('children')).order_by('-children__count')
If you need access to the child instances themselves, you may also want to look at doing a qs.prefetch_related('children')
as well.

DylanYoung
- 2,423
- 27
- 30
-
It's also worth noting that if your hierarchy is indeed only two levels deep, you probably don't get any benefit from mptt as a simple parent field and order field should suffice and be more performant... though I could be wrong. – DylanYoung Aug 08 '17 at 18:13
3
something like this should do it:
from mptt.templatetags.mptt_tags import cache_tree_children
qs = qs.filter(level__lt=2)
root_nodes = cache_tree_children(qs)
root_nodes.sort(key=lambda node: len(node.get_children()), reverse=True)

craigds
- 2,072
- 14
- 25