@register.filter
def tree_queryset(value):
    """
    Converts a normal queryset from an MPTT model to include all the ancestors
    so a filtered subset of items can be formatted correctly
    """
    from django.db.models.query import QuerySet
    from copy import deepcopy
    if not isinstance(value, QuerySet):
        return value

    qs = value
    qs2 = deepcopy(qs)
    # Reaching into the bowels of query sets to find out whether the qs is
    # actually filtered and we need to do the INCLUDE_ANCESTORS dance at all.
    # INCLUDE_ANCESTORS is quite expensive, so don't do it if not needed.
    is_filtered = bool(qs.query.where.children)
    if is_filtered:
        include_pages = set()
        # Order by 'rght' will return the tree deepest nodes first;
        # this cuts down the number of queries considerably since all ancestors
        # will already be in include_pages when they are checked, thus not
        # trigger additional queries.
        for p in qs2.order_by('rght').iterator():
            if p.parent_id and p.parent_id not in include_pages and p.id not in include_pages:
                ancestor_id_list = p.get_ancestors().values_list('id', flat=True)
                include_pages.update(ancestor_id_list)

        if include_pages:
            qs = qs | qs.model._default_manager.filter(id__in=include_pages)

        qs = qs.distinct()
    return qs
dataset/ETHPy150Open callowayproject/django-categories/categories/templatetags/category_tags.py/tree_queryset/original