When you use tags to your Wagtail application, you might have the requirement to get a count of the tags. We are using the taggit
and modelcluster
modules in this example.
Let's start with the following model declaration:
blog/models.py
from django.db import modelsfrom django.db.models.aggregates import Count from modelcluster.fields import ParentalKeyfrom modelcluster.contrib.taggit import ClusterTaggableManagerfrom taggit.models import Tag, TaggedItemBase from wagtail.core.models import Page class BlogPostTag(TaggedItemBase): content_object = ParentalKey('BlogPost', related_name='tagged_items', on_delete=models.CASCADE) class BlogPost(Page): tags = ClusterTaggableManager(through=BlogPostTag, blank=True)
To get all tags along with their related blog post count, you can execute:
Tag.objects.all().annotate( num_times=Count('blog_blogposttag_items'))
This gives you a list of all tags with the number of blog posts using it in the property num_times
.
If you want to do something similar for a specific blog post, you can do:
Tag.objects.all().annotate( num_times=Count('blog_blogposttag_items')).filter(blogpost=post)