我实际上正在使用Django-Tagging进入我的django应用程序。我想知道你是否知道打印最常见标签的方法。我尝试了Django-Taggit-Templatetags,但它不起作用......(这里是my unanswered question about it)。有人能帮助我吗?
答案 0 :(得分:2)
Django 1.10,Python 3.5,django-taggit 0.21.3
YourModel.tags.most_common()
和前10个标签:
YourModel.tags.most_common()[:10]
答案 1 :(得分:1)
我的解决方案可能是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