Django-Tagging - counting and arranging top tags (is there a cleaner solution for mine?)

I use Django-Tagging and I don’t need a cloud, I just need a limited list of the most popular tags used on my blogs.

Using the following:

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

It returns an array (note that I use Lorem Ipsum during development):

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

But then, to order and restrict it, I have to do the following:

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 an easier way to do this? I feel it should be.

+3
source share
6 answers

A django {% regroup %}tag template may be useful for this. Assuming what tagsis 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 %}
+3
source

django, . http://docs.djangoproject.com/en/dev/topics/db/aggregation .

Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
+5

, , . , , abeyer

import operator
tags = Tag.objects.usage_for_model(Post, counts=True)
tags.sort(key=operator.attrgetter('count'), reverse=True)
+3

, n - , Fragsworth - , , . - , , , ... "ORDER BY count DESC LIMIT n" , , .

However, it seems that django-tagging is hardcoded to always group / sort identifiers and tag names. I would say that the correct solution is to file an error against it, and get an open api that will return you the top n tags.

+1
source

I use raw sql for this:

trends = Tag.objects.raw("select tagging_tag.id, count(object_id) as counter from tagging_tag left join tagging_taggeditem on tagging_tag.id = tagging_taggeditem.tag_id group by tagging_tag.id order by counter DESC limit 10")
0
source

My approach for getting top tags in Django-Tagging:

top_tags = Tag.objects.annotate(num=Count('taggit_taggeditem_items')).order_by('-num')
0
source

Source: https://habr.com/ru/post/1725512/


All Articles