Search code examples
django-admindjango-mptt

Django admin + MPTT : How to display children when filtering a parent node?


I set up 2 models Article and Taxonomy. Taxonomy is an MPTTModel Subclass.

All is working fine except one thing : If I select a parent node that has no Article linked to it it will not display Articles linked to children nodes.

So I am trying to code my custom filter but I get stuck with queryset filtering. How can I filter this queryset to display all Articles linked to children Nodes IF I click on a parent node ? :

class TaxonomyFilter(SimpleListFilter):
    """
    Return incremented taxonomy list. Filtering by parent node display all children.
    """
    title = ('Index')
    parameter_name = 'node_id'

    def lookups(self, request, model_admin):
        taxos = Taxonomy.objects.all()
        leafs = []
        for taxo in taxos:
            leafs.append((taxo.id,(taxo.name)))

        return leafs


    def queryset(self,request,queryset):
        """
        Filter list by displaying children if parent node has any.
        """
        if self.value():
            return queryset.filter()  
        else:
            return queryset

Solution

  • Julius: This is a bit lower-level, but does less queries than your solution (2 instead of 3)

    def queryset(self, request, queryset):
        """
        Filter list by displaying children if parent node has any.
        """
        t = Taxonomy.objects.get(pk=self.value())
    
        return queryset.filter(taxonomy__lft__gte=t.lft, taxonomy__rght__lte=t.rght)