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.
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)
精彩评论