Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and MPTT - get only leaf nodes

I'm new to Django and MPTT and having hard time figuring out how to get all leaf nodes and send them directly to Form class. For example, I have created MPTT Category Model, and have hierarchy like this:

  • Category1
    • Category2
    • Category3
  • Category4
    • Category5
    • Category6

So I want only to get leaf categories(cat2,3,5,6).My Form class looks something like this:

class UploadForm(forms.Form):
    description = forms.CharField(max_length=50)
    category = mpttform.TreeNodeMultipleChoiceField(queryset=Category.objects.all())
    file = forms.FileField() 

And with queryset=Category.objects.all() I get exactly the same thing above - all Categories and its children.Is there a way I can get only leaf nodes(children), but leaf nodes from ALL categories, not from specific Category instance ? Thanks.

like image 921
Zed Avatar asked Jun 02 '12 14:06

Zed


3 Answers

not used django mptt in a while, but given that a leaf node may be identified by right == left + 1, you should be able to filter for this using an F() expression

like image 59
second Avatar answered Sep 26 '22 05:09

second


Category.objects.filter(children__isnull=True)
like image 37
Arpit Singh Avatar answered Sep 24 '22 05:09

Arpit Singh


Unoptimal solution:

Category.objects.filter(id__in=[category.id for category in Category.objects.all() if category.is_leaf_node()])
like image 38
MrKsn Avatar answered Sep 26 '22 05:09

MrKsn