Dicky Raambo
Dicky Raambo

Reputation: 523

call ForeignKey and count it on django template

I want to count that how many employees in every department and show it on django template.

here my models.py

class Company(models.Model):

    name = models.CharField(max_length=100)
    desc = models.TextField(blank=True, null=True, default='Tidak ada deskripsi')

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("system:company_list")

class Employee(models.Model):
    name = models.CharField(max_length=100)
    company = models.ForeignKey(Company, default=0, on_delete=models.SET_DEFAULT, related_name='company')

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("system:detail",kwargs={'pk':self.pk})

and here my views.py

class CompanyListView(ListView):
    context_object_name = 'companys'
    model = models.Company

and here my company_list.html

{% for company in companys %} 

<tr>
    <td>{{ company.name }}</td>
    <td>{{ companys.employee.count }}</td>
    <td>{{ company.desc }}</td>
</tr>

{% endfor %}

Iam trying count the company with {{ companys.count }} and its work. and i think it will gonna be {{ companys.employee.count }} for counting the employee. but its dint work.

did i miss something?...

Upvotes: 0

Views: 169

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

You should put {{ company.company.count }} to have it work, because of your related_name : company = models.ForeignKey(Company, default=0, on_delete=models.SET_DEFAULT, related_name='company')

More info can be found here

It's suggested, but not required, that the name of a related_name be a plural of the current model

class Employee(models.Model):
    name = models.CharField(max_length=100)
    company = models.ForeignKey(Company, default=0, on_delete=models.SET_DEFAULT, related_name='employees')

So it that case, you would have in template

{{ company.employees.count }} # count
{{ company.employees.all }} # All employees

Upvotes: 1

Related Questions