Python, Django: hierarchical tree structure

I’m trying to create a web page that displays an employee hierarchy in a tree-like structure using Python and Django. My code looks like this:

models.py:

class Employee(models.Model):
    name = models.CharField(max_length=100)
    position = models.CharField(max_length=100)
    hire_date = models.DateField()
    salary = models.DecimalField(max_digits=8, decimal_places=2)
    manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='subordinates')

views.py:

def employee_hierarchy(request):
    employees = Employee.objects.select_related('manager').all()
    return render(request, 'employees/employee_hierarchy.html', {'employees': employees})

employee_hierarchy.html:

<body>
   <h1>Employee Hierarchy</h1>
   <ul>
       {% for employee in employees %}
           {% include 'employees/employee_item.html' with employee=employee %}
       {% endfor %}
   </ul>
</body>

employee_item.html:

<li>{{ employee.name }} ({{ employee.position }}) - Manager: {% if employee.manager %}{{ employee.manager.name }}{% endif %}</li>
{% if employee.subordinates.all %}
   <ol>
       {% for subordinate in employee.subordinates.all %}
           {% include 'employees/employee_item.html' with employee=subordinate %}
       {% endfor %}
   </ol>
{% endif %}

I’m a beginner in programming. Where is the best place to implement the logic: in the model, view, or template? How can views.py and the employee_hierarchy.html template look like to display the employee hierarchy in a tree-like structure?

Thank you in advance!

The best place to implement the logic for displaying the employee hierarchy in a tree-like structure is in the template.

To modify the views.py and employee_hierarchy.html template to display the employee hierarchy in a tree-like structure, you can make use of recursion in the template. Here’s an updated version of the code:

views.py:

def employee_hierarchy(request):
    root_employee = Employee.objects.filter(manager=None).first()
    return render(request, 'employees/employee_hierarchy.html', {'root_employee': root_employee})

employee_hierarchy.html:

<body>
   <h1>Employee Hierarchy</h1>
   <ul>
       {% include 'employees/employee_item.html' with employee=root_employee %}
   </ul>
</body>

employee_item.html:

<li>{{ employee.name }} ({{ employee.position }}) - Manager: {% if employee.manager %}{{ employee.manager.name }}{% endif %}</li>
{% if employee.subordinates.all %}
   <ol>
       {% for subordinate in employee.subordinates.all %}
           {% include 'employees/employee_item.html' with employee=subordinate %}
       {% endfor %}
   </ol>
{% endif %}

With this updated code, the employee_hierarchy.html template starts with the root employee and includes the employee_item.html template recursively for each subordinate employee. This will display the employee hierarchy in a tree-like structure.