Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

How to get a count of all objects set with a specific value in field in Django template?

I want to get a count of all objects set that are False for the object field adult.

I am looping over the "Family" model in my template:

class Family(models.Model):
    name = models.CharField(max_length=255)

class Person(models.Model):
    family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='person', related_query_name='person')
    adult = models.BooleanField()

Here is what I want to achieve in the template:

# views.py
families = Family.objects.all()
# index.html

{% for family in families %}
    {{ family.name }} has {{ family.person(adult=False).count() }} non-adults!
{% endfor %}

Upvotes: 0

Views: 148

Answers (1)

Chris
Chris

Reputation: 2212

If I understand you correctly I think your problem is best solved by using django annotatations (for details see the docs).

In your view annotate each Family object with the numer of adults:

families = Family.objects.annotate(non_adults=Count('person', filter=Q(person__adult=False)))

Then you can simply use this annotation in your template

{% for family in families %}
    {{ family.name }} has {{ family.non_adults }} non-adults!
{% endfor %}

With annotations you can utilize the power of the database which is often more effective than querying and doing additional things in python.

Upvotes: 3

Related Questions