Django-Tagging - 计算并订购顶级"标签"(我的清洁解决方案是否有用?)

Key*_*upt 3 python django django-tagging

我正在使用Django-Tagging,我并不需要云,我只想要一个有限的列表,列出我的博客条目中最常用的标签.

使用以下内容:

[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
Run Code Online (Sandbox Code Playgroud)

它返回一个数组(注意我在开发时使用的是Lorem Ipsum):

[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]
Run Code Online (Sandbox Code Playgroud)

但是,为了订购和限制它,我需要这样做:

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]
Run Code Online (Sandbox Code Playgroud)

有没有更简洁的方法来做到这一点?我觉得必须有.

May*_*esh 5

如果您使用的是最新版本的django,则可以使用聚合.http://docs.djangoproject.com/en/dev/topics/db/aggregation该页面上的一个示例..

Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
Run Code Online (Sandbox Code Playgroud)