0

I got following output from django-mptt tree:

Group-2    
    Ministry E
        Division G
        Division Z
    Ministry F
        Division I
        Division J

Group-3    
    Ministry P
        Division X
        Division Y
    Ministry Q
    Ministry R
        Division U
        Division V

But I want to show it as follows:

        Division G
        Division Z

        Division I
        Division J 

        Division X
        Division Y

    Ministry Q

        Division U
        Division V

That means level 1 only shows when level 2 not exists otherwise level 2 only shows. I tried using Model.objects.filter(level=1) but it gives only one level not both selectively. I also tried Model.objects.filter(level__gt=0) it gives both level not obey the condition.

How can I get both level maintaining conditions?

EDIT:

{% block content %}


{% load mptt_tags %}
{% for instance in Genre.objects.all %}
    {% if instance.is_leaf_node %}
        {{ instance }}
    {% endif %}
{% endfor %}

{% endblock %}

Views:

def show_genres(request):
    instances = Genre.objects.filter(children__isnull=True)
    return render(request,
                  'genre/template.html', {'instances': instances})

URLS:

url(r'^genres/$', show_genres, name="genre_list",)

Model:

 class Genre(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

class MPTTMeta:

    order_insertion_by=['name']
ohid
  • 824
  • 2
  • 8
  • 23

1 Answers1

0

Show only the leaf nodes

Solution #1 - in template:

{% for instance in Model.objects.all %}
    {% if instance.is_leaf_node %}
        {{ instance }}
    {% endif %}
{% endfor %}

Solution #2 - in view:

instances = Model.objects.filter(children__isnull=True)
return render(request, 'template.html', {'instances': instances})
Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39