【问题标题】:Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?)Django-Tagging - 计算和排序顶级“标签”(有更清洁的解决方案吗?)
【发布时间】:2009-12-13 05:31:03
【问题描述】:

我正在使用 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]

有没有更简洁的方法来做到这一点?我觉得应该有。

【问题讨论】:

    标签: python django django-tagging


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      Django 的{% regroup %} 模板标签可能对此有用。假设 tags 在您的模板上下文中:

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

      【讨论】:

        【解决方案3】:

        我发现下面的排序代码比你写的更易读。当然它并没有消除abeyer所说的源问题

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

        【讨论】:

          【解决方案4】:

          如果你无论如何都需要拉出所有标签,并且限制到前 n 只是一个演示的东西,Fragsworth 的答案可能是要走的路。如果您没有在其他地方使用其余的标签,我认为这确实是数据库查询中应该发生的事情……您可能希望在查询以避免拉出一堆你不会使用的标签。

          然而,django-tagging 似乎被硬编码为始终按标签 ID 和名称进行分组/排序。我想说正确的解决方案是针对它提交一个错误,然后公开一个 api,它会给你返回前 n 个标签。

          【讨论】:

            【解决方案5】:

            我为此使用原始 sql:

            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")
            

            【讨论】:

              【解决方案6】:

              我在 Django-Tagging 中获取顶级标签的方法是:

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2015-12-11
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-01-05
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多