[Django]-Better way to delete unused tag. / django taggit python

6👍

You can delete unused tags with:

from django.db.models import Count
from taggit.models import Tag

class PostDelete(WriterCheckMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('blog:list')

    def delete(self, request, *args, **kwargs):
        try:
            return super().delete(request, *args, **kwargs)
        finally:
            Tag.objects.annotate(
                ntag=Count('taggit_taggeditem_items')
            ).filter(ntag=0).delete()

This will thus annotate the queryset, and remove the tags with no related items.

That being said, I am not sure why you per se need to remove unused tags. You can decide to only render tags that have one item. But storing tags in the database, will normally not result in large amounts of disk usage anyway.

Leave a comment