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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With