[Django]-Django taggit aggregation query to return count per tag

3👍

You can filter the annotation with:

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

Tag.objects.annotate(
    nmeal=Count('meal', filter=Q(meal__is_cooked=True))
)

The Tag objects that arise from thsi queryset will have an extra attribute .nmeals that contains the number of cooked meals.

If you only want to retrieve Tag objects where there is at least one related cooked meal, you can work with:

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

Tag.objects.filter(
    meal__is_cooked=True
).annotate(
    nmeal=Count('meal')
)

Leave a comment