Search code examples
djangodjango-templatesdjango-mpttdjango-filter

Django-mptt filter child from django template


I have used django-mptt to represent my hierarchical data. To get the data from database table I have used following code from my template.

{% load mptt_tags %}
{% recursetree nodes %} 
{{ node.name }}
{% endrecursetree %} 

Now I want to filter children by the id and I need only one immediate child to display in my template.how can I do this from my template?


Solution

  • level property and get_previous_sibling can be used to achieve this:

    {% load mptt_tags %}
    
    {% recursetree nodes %}
    
      {% if node.level == 0 %}
        {# first level #}
        {{ node.name }}
      {% elif not node.get_previous_sibling %}
        {# first child #}
        {{ node.name }}
      {% endif %}
    
      {{ children}}
    {% endrecursetree %}
    

    Please note that get_previous_sibling call will trigger db query.