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.
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
Category.objects.filter(children__isnull=True)
Unoptimal solution:
Category.objects.filter(id__in=[category.id for category in Category.objects.all() if category.is_leaf_node()])
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