Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django taggit, listing count for each tag

Let's say I have three tags. I want to show how many objects are linked to it. Like so:

Apple (3)
Orange (0)
Banana (5)

How do I make it work the simplest way possible, preferably without creating new attributes in the database?

I'm guessing I'll need to iterate through all the tags, count them, and put both together inside a dictionary, right? Eg:

something = {'apple': X, 'orange': X, etc...

Then make that available in the context, so that it's accessible in the HTML template? Or is there a simpler way? Thank you!

like image 901
Bob Avatar asked Feb 07 '23 08:02

Bob


1 Answers

I did this with an annotated queryset.

queryset = Tag.objects.all()
queryset2 = queryset.annotate(num_times=Count('taggit_taggeditem_items'))

You can then make a dictionary if you want to:

mydict = {}
for tag in querset2:
    mydict[tag.name] = tag.num_times
like image 192
joel.schopp Avatar answered Feb 20 '23 04:02

joel.schopp