Search code examples
pythondjangodjango-tagging

Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?)


I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries.

Using the following:

[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]

It returns an array (note I'm using Lorem Ipsum while I develop):

[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]

But then to order and limit it I need to then do this:

sorted([(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)], key=lambda k:k[1], reverse=True)[:10]

Is there a neater way to do this? I feel like there must be.


Solution

  • Django's {% regroup %} template tag might be useful for this. Assuming tags is in the context of your template:

    {% regroup tags|dictsort:"count" by count as sorted_tags %}
    ...
    {% for count in sorted_tags %}
    ...
        {% for tag in count %}
        ...
        {% endfor %}
    {% endfor %}