'Django access related items in template

Please help me I’m stuck in understanding how Django ORM works.

Here is my very simple models:

class Department(models.Model):
    title = models.CharField(max_length=50)


class Employee(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    department = models.ForeignKey(Department, on_delete=models.PROTECT)

I want a template that looks like:
Department 1

  • Employee 1
  • Employee 2

Department 2

  • Employee 3
  • Employee 4

But I can’t figure out what I should do in my view and(or) template



Solution 1:[1]

You should use a ListView:

from django.views.generic import ListView

class DepartmentListView(ListView):
    model = Department

Create a template within your apps directory. Within your template you have access to {{ object_list }} which is a list (QuerySet) of your Department objects. So you could use:

{% for department in object_list %}
    {{ department.title }}

    {% for employee in department.employee_set.all %}
        {{ employee.first_name }}
    {% endfor %}
{% endfor %}

You probably should start by going through the official django tutorial, it will greatly explain everything you neet to get startet.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1