djangodjango-mptt

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:

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.


Solution

  • 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