[Fixed]-Django and MPTT – get only leaf nodes

21👍

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

👤second

15👍

Category.objects.filter(children__isnull=True)

2👍

Unoptimal solution:

Category.objects.filter(id__in=[category.id for category in Category.objects.all() if category.is_leaf_node()])
👤MrKsn

0👍

My little snippet for django mptt

from django.db import models

class CategoryManager(models.Manager):
    def get_leaf(self, level=2):
        return self.filter(level__lte=level).order_by('tree_id','lft').all()

class Category(models.Model):
     objects = CategoryManager()

profit, use it: Catalog.objects.get_leaf()

0👍

From docs:

is_leaf_node()

Returns True if this model instance is a leaf node (it has no children), False otherwise.

Leave a comment