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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With