Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

template:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {% 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 %}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading