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!