繁体   English   中英

Django-Taggit:如何打印最常用的标签?

[英]Django-Taggit: How to print the most used tags?

我实际上在我的django应用程序中使用Django-Tagging 我想知道你是否知道打印最常见标签的方法。 我尝试过Django-Taggit-Templatetags,但它不起作用......(这是我未提出的问题 )。 有人能帮我吗?

Django 1.10,Python 3.5,django-taggit 0.21.3

YourModel.tags.most_common()

和前10个标签:

YourModel.tags.most_common()[:10]

我的解决方案可能是hacky,但它确实有效。 尝试:

from collections import defaultdict, Counter
from taggit.models import Tag
from .models import YourModel

tag_frequency = defaultdict(int)


for item in YourModel.objects.all():
    for tag in item.tags.all():
        tag_frequency[tag.name] += 1

Counter(tag_frequency).most_common()

因此,在基于类的视图中,这可能如下所示:

from collections import defaultdict, Counter
from taggit.models import Tag
from .models import YourModel


class YourView(ListView):
    model = YourModel
    context_object_name = "choose_a_name_you_like"
    template_name = "yourmodel/yourmodel_list.html"

    def get_context_data(self):
        context = super(YourView, self).get_context_data() # assigns the original context to a dictionary call context
        tag_frequency = defaultdict(int)

        for item in YourModel.objects.all():
            for tag in item.tags.all():
                tag_frequency[tag.name] += 1

        context['tag_frequency'] = Counter(tag_frequency).most_common() # adds a new item with the key 'tag_frequency' to the context dictionary, which you can then access in your template
        return context

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM