Django-Tagging - 对顶级“标签”进行计数和排序(有更清洁的解决方案吗?)
我正在使用 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]
有没有更简洁的方法来做到这一点?我感觉一定有。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用的是最新版本的 django,则可以使用聚合。 http://docs.djangoproject.com/en/dev/topics/db/aggregation 该页面上的一个示例..
If you are using the latest version of django, you could use aggregation. http://docs.djangoproject.com/en/dev/topics/db/aggregation an example on that page ..
Django 的
{% regroup %}
模板标签对此可能有用。假设tags
位于模板的上下文中:Django's
{% regroup %}
template tag might be useful for this. Assumingtags
is in the context of your template:我发现下面的排序代码比您编写的代码更具可读性。当然,这并不能消除 abeyer 所说的源问题
I find the following sorting code a bit more readable than the one you wrote. Of course it doesn't remove the source problem stated by abeyer
如果您无论如何都需要提取所有标签,并且对前 n 个标签的限制只是一个演示问题,那么 Fragsworth 的答案可能是正确的选择。如果您没有在其他地方使用其余标签,我认为这确实应该在数据库查询中发生......您可能希望在以下位置执行“ORDER BY count DESC LIMIT n”查询以避免拉出一堆您不会使用的标签。
然而,django-tagging 似乎被硬编码为始终按标签 ID 和名称进行分组/排序。我想说正确的解决方案是针对该问题提交一个错误,并公开一个 api,该 API 将为您返回前 n 个标签。
If you need to pull all the tags anyway, and the limit to the top n is simply a presentation thing, Fragsworth's answer is probably the way to go. If you aren't using the remainder of the tags somewhere else, I'd argue that this is really something that should be happening in the database query...you would want to be doing an 'ORDER BY count DESC LIMIT n' on the query to avoid pulling a bunch of tags that you aren't going to use.
However, it appears that django-tagging is hard coded to always group/sort by tag ids and names. I'd say the right solution is to file a bug against that, and get an api exposed that will give you back the top n tags.
我为此使用原始 sql:
I use raw sql for this:
我在 Django-Tagging 中获取顶级标签的方法是:
My approach for getting top tags in Django-Tagging is: