Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-MPTT - ordering root nodes by count of immediate descendants

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.

like image 566
NFicano Avatar asked Jun 29 '11 18:06

NFicano


1 Answers

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.

like image 123
DylanYoung Avatar answered Sep 28 '22 11:09

DylanYoung