Question

I'm using django-taggit to tag items in a todo list app.

I'm trying to list each of the tags along with the number of actions associated with each tag so that it may read:

Tag A (1)
Tag B (3)
Tag C (2)

Tag A has 1 item, Tag B has 3, etc.

I added a boolean field to django-taggit. So now I'm getting a list of tags like this:

visible_tags = Tag.objects.filter(visible=True).order_by('name')
hidden_tags = Tag.objects.filter(visible=False).order_by('name')

I can get the count of items (actions) like this:

for tag in visible_tags:
    print tag
    print Action.objects.filter(tags__name__in=[tag]).count()

Now I want to attach these counts to the visible_tags and hidden_tags set so that I can iterate over them in the template like this:

{% for tag in visible_tags %}
    {{ tag }} ({{ tag.count }})<br>
{% endfor %}

How can I attach a .count value to each tag within visible_tags and within hidden_tags? I assume I have to iterate over all the tags in each set?

Was it helpful?

Solution

Use annotations: https://docs.djangoproject.com/en/dev/topics/db/aggregation/

from django.db.models import Count

Tag.objects.annotate(action_count=Count('action'))

(You might have to tweak that a bit. I'm guessing on the related name for Action)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top