我正在使用Django-Tagging,我并不需要一个云,我只想要一个在我的博客条目中使用的最受欢迎的标签的有限列表。
使用以下内容:
[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]它返回一个数组(注意,我在开发时使用了Lorem Ipsum ):
[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]但是为了订购和限制它,我需要这样做:
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]有没有更好的方法来做到这一点?我觉得肯定会有的。
发布于 2009-12-13 13:52:36
Django的{% regroup %}模板标记可能对此很有用。假设tags位于模板的上下文中:
{% regroup tags|dictsort:"count" by count as sorted_tags %}
...
{% for count in sorted_tags %}
...
{% for tag in count %}
...
{% endfor %}
{% endfor %}发布于 2009-12-14 15:03:28
如果您使用的是最新版本的django,则可以使用聚合。在那个页面上http://docs.djangoproject.com/en/dev/topics/db/aggregation一个例子..
Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')发布于 2010-01-14 22:22:06
我发现下面的排序代码比您编写的代码更具可读性。当然,它并不能消除abeyer所说的源问题
import operator
tags = Tag.objects.usage_for_model(Post, counts=True)
tags.sort(key=operator.attrgetter('count'), reverse=True)https://stackoverflow.com/questions/1895638
复制相似问题