Im actually using Django-Tagging into my django app. I would like to know if you know some way to print the most common tags. I tried Django-Taggit-Templatetags but it doesn't work ... (here is my unanswered question about it ). Can someone help me?
Django 1.10, Python 3.5, django-taggit 0.21.3
YourModel.tags.most_common()
and top 10 tags:
YourModel.tags.most_common()[:10]
My solution might be hacky but it works. Try:
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()
So in a Class-based view this might look like:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.