#django #python #wagtail

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

 1from django.db import models
 2from django.db.models.aggregates import Count
 3
 4from modelcluster.fields import ParentalKey
 5from modelcluster.contrib.taggit import ClusterTaggableManager
 6from taggit.models import Tag, TaggedItemBase
 7
 8from wagtail.core.models import Page
 9
10class BlogPostTag(TaggedItemBase):
11    content_object = ParentalKey('BlogPost', related_name='tagged_items', on_delete=models.CASCADE)
12
13class BlogPost(Page):
14    tags = ClusterTaggableManager(through=BlogPostTag, blank=True)

To get all tags along with their related blog post count, you can execute:

1Tag.objects.all().annotate(
2    num_times=Count('blog_blogposttag_items')
3)

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:

1Tag.objects.all().annotate(
2    num_times=Count('blog_blogposttag_items')
3).filter(blogpost=post)