Access Foreign Key count in Django Template

I have two models: Farm and Animal with a ForeignKey relation. Each Farm contains x animals.

I'm doing a table in the frontend with a for loop of each farm. How can I show the number of animals in each farm? models:

class Farm(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None)
    square_meter = models.IntegerField(blank=True, null=True)
    friendly_name = models.CharField(max_length=24, blank=True)

    kml = models.FileField(upload_to=user_directory_path_kml, null=True, blank=True)

class Animal(models.Model):

    class Meta:
        verbose_name_plural = "Animals"

    farm = models.ForeignKey(Farm, on_delete=models.CASCADE, blank=True, null=True, default=None)

    name = models.CharField(max_length=24, blank=True)
    datetime = models.DateTimeField(blank=True, null=True,
    tracking = models.BooleanField(default=False)
    kg = models.IntegerField(blank=True, null=True)


 {% for farm in farms %}
                       <th scope="row">{{forloop.counter}}</th>
                       <td>{{farm. }}</td> # Here I want animal count
                    {% endfor %}

Since you did not specify a related_name for the farm foreign key of Animal you can use the default foreign key manager <class name>_set. This manager has a count method. So

{{ farm.animal_set.count }}

should provide the count of animals for each farm.

Back to Top