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:


from django.db import models
from django.db.models.aggregates import Count

from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from 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:


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:


Related Posts

  • Defining custom settings in Wagtail
  • Making publish the default action in Wagtail
  • Migrating your Wagtail site to a different database engine
  • Programatically creating redirects in Wagtail
  • Change the Wagtail site domain via a management command