I recently asked for how to get count on filetered subqueries in a template and got an answer here: Get count on filtered subqueries in template
Now I realised that I need this extended as following (which I think is a lot mroe than my first question, therefor creating a new one here):
- Show articles that doesn't match the tag, but then with 0 as count.
- Extend to allow counting on different tags.
With the following model:
class Category(models.Model):
...
class SubCategory(models.Model):
category = models.ForeignKey(Category)
....
class Tag(models.Model):
....
class Article(models.Model)
sub_category = models.ForeignKey(SubCategory)
tag = models.ForeignKey(Tag)
I got the following answer (views.py), which will create a num_articles variable that holds the count of number of articles with tag='xyz':
def my_view(request, other, arguments):
...
subcategories = category.sub_category_set.filter(tag__tagname='xyz')
.annotate(num_articles=Count('article__id'))
And the template:
{% for subcategory in subcategories %}
{{ subcategory.name }} -- {{ subcategory.num_articles }}
{% endfor %}
But now, I want to be able to do something like this, make independent counts on several different tags, so that the count of 'xyz' is not dependent on the count on 'abc', and vice versa:
def my_view(request, other, arguments):
...
subcategories = category.sub_category_set.
filter(tag__tagname='xyz').annotate(num_articles_xyz=Count('article__id'))
filter(tag__tagname='abc').annotate(num_articles_abc=Count('article__id'))
filter(tag__tagname='def').annotate(num_articles_def=Count('article__id'))
...
To use in the template as:
{% for subcategory in subcategories %}
{{ subcategory.name }} -- {{ subcategory.num_articles_xyz }}<br />
{{ subcategory.num_articles_abc }} -- {{ subcategory.num_articles_def }}
...
{% endfor %}
And also want all the subcategories to be shown, even if there is no match in any of the counts. But, then with a value of 0 for that count.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…