Agregar valor de recuento para configurar

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?

preguntado el 09 de marzo de 12 a las 14:03

1 Respuestas

Usar anotaciones: 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)

respondido 09 mar '12, 14:03

that's what i thought but i don't think aggregation works with django-taggit? django-taggit.readthedocs.org/en/latest/api.html#aggregation - JamesO

It might. The documented problem is with the opposite relation, i.e. if the OP wanted to count tags on Action: Action.objects.annotate(Count('tags')). - Chris Pratt

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.