Home > Enterprise >  Django get count of related objects with value and add it to an annotation
Django get count of related objects with value and add it to an annotation

Time:05-22

If I want to annotate the number of related objects to each parent object, I would do this:

Agent.objects.annotate(deal_count=Count('deal'))

If my Deal objects have a closed boolean, how would I annotate the number of deals marked as closed?

CodePudding user response:

You can work with the filter=… parameter [Django-doc]:

from django.db.models import Q

Agent.objects.annotate(deal_count=Count('deal', filter=Q(deal__closed=True)))

or if you want to annotate with both counts:

from django.db.models import Q

Agent.objects.annotate(
    deal_count=Count('deal'),
    closed_deal_count=Count('deal', filter=Q(deal__closed=True))
)
  • Related