Home > other >  Access Foreign Key count in Django Template
Access Foreign Key count in Django Template

Time:12-22

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, default=datetime.now)
    tracking = models.BooleanField(default=False)
    kg = models.IntegerField(blank=True, null=True)

template:

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

CodePudding user response:

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.

  • Related