Get Count On Filtered Subqueries In Template
If I have a parent model and a child model, how can I then list all child objects of a parent object, and have a filtered count for each child object, when listing them? To give an
Solution 1:
You're right that you'll have to do this in the view. You can use annotation to get the number of filtered articles for each subcategory:
from django.db.models import Count
defmy_view(request, other, arguments):
...
subcategories = category.sub_category_set.filter(tag__tagname='xyz') \
.annotate(num_articles=Count('article__id'))
...
Pass subcategories
to your template context, and in your template you can do this:
{% for subcategory in subcategories %}
{{ subcategory.name }} -- {{ subcategory.num_articles }}
{% endfor %}
Post a Comment for "Get Count On Filtered Subqueries In Template"