Skip to content

Instantly share code, notes, and snippets.

@afparsons
Created September 23, 2021 02:15
Show Gist options
  • Save afparsons/d8510f5c065e3bd3772010ba5348402c to your computer and use it in GitHub Desktop.
Save afparsons/d8510f5c065e3bd3772010ba5348402c to your computer and use it in GitHub Desktop.
Get 'django-taggit' tag counts for each django model type
from typing import Dict
from pandas import DataFrame
from taggit.models import TaggedItem
from django.db.models import Q, Count
def get_tag_counts() -> DataFrame:
"""
Returns a DataFrame with the counts of django-taggit TaggedItems by
Tag name and ContentType model name.
Example:
>>> tag__name modela modelb
... 0 tag_1 123 9876
... 1 tag_2 4567 54
... 2 tag_3 89 321
"""
annotations: Dict[str, Count] = {
model_name: Count('id', filter=Q(content_type__model=model_name))
for model_name in TaggedItem.objects
.distinct('content_type__model')
.values_list('content_type__model', flat=True)
}
dataframe: DataFrame = DataFrame(
TaggedItem.objects
.values('tag__name')
.order_by()
.annotate(**annotations)
)
return dataframe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment