diff --git a/apps/tag/services/tag_batch_service.py b/apps/tag/services/tag_batch_service.py index 46aca15..dc19ce7 100644 --- a/apps/tag/services/tag_batch_service.py +++ b/apps/tag/services/tag_batch_service.py @@ -1,4 +1,4 @@ -from django.db.models import Sum, Q, Count, QuerySet +from django.db.models import Sum, Q, Count, QuerySet, OuterRef, Subquery, IntegerField from django.db.models.functions import Coalesce from apps.authentication.models import Organization @@ -26,9 +26,7 @@ class TagBatchService: base_data = qs.aggregate( batch_count=Count('id', distinct=True), total_distributed_tags=Coalesce(Sum('total_distributed_tags'), 0), - total_remaining_tags=Coalesce(Sum('total_remaining_tags'), 0) / - Coalesce(Sum('total_remaining_tags', distinct=True), 0), - tag_count_created_by_batch=Count('tag'), + total_remaining_tags=Coalesce(Sum('total_remaining_tags'), 0), has_distributed_batches_number=Count( 'id', distinct=True, @@ -37,21 +35,30 @@ class TagBatchService: ]) ) ) + base_data.update(qs.aggregate(tag_count_created_by_batch=Count('tag'))) + + tag_count_subquery = ( + TagBatch.objects + .filter(id=OuterRef('id')) + .annotate(cnt=Count('tag')) + .values('cnt') + ) species_data = ( qs + .annotate( + tag_count=Subquery(tag_count_subquery, output_field=IntegerField()) + ) .values('species_code') .annotate( batch_count=Count('id', distinct=True), total_distributed_tags=Coalesce(Sum('total_distributed_tags'), 0), total_remaining_tags=Coalesce(Sum('total_remaining_tags'), 0), - tag_count_created_by_batch=Count('tag'), + tag_count_created_by_batch=Coalesce(Sum('tag_count'), 0), has_distributed_batches_number=Count( 'id', distinct=True, - filter=Q(status__in=[ - 'distributed' - ]) + filter=Q(status='distributed') ) ) .order_by('species_code')