From bf845895ff7f1325a5bf979de88bb6b1a43358e3 Mon Sep 17 00:00:00 2001 From: Mohammad Nour Massri Date: Fri, 10 Jan 2025 01:25:24 -0500 Subject: [PATCH] fixing query in scrimmage record, win/loss/tie (#898) --- backend/siarnaq/api/compete/views.py | 38 +++++++++++++++------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/backend/siarnaq/api/compete/views.py b/backend/siarnaq/api/compete/views.py index 0d719380b..672e69839 100644 --- a/backend/siarnaq/api/compete/views.py +++ b/backend/siarnaq/api/compete/views.py @@ -13,7 +13,6 @@ Q, Subquery, Sum, - Value, When, ) from django.db.models.functions import Coalesce @@ -674,23 +673,26 @@ def scrimmaging_record(self, request, pk=None, *, episode_id): .exclude(participants__team__status=TeamStatus.INVISIBLE) ) - # Annotate the queryset to perform logic on the database side - results = queryset.annotate( - this_team_score=Sum( - Case( - When(participants__team_id=team_id, then="participants__score"), - default=Value(0), - output_field=IntegerField(), - ) - ), - other_team_score=Sum( - Case( - When(~Q(participants__team_id=team_id), then="participants__score"), - default=Value(0), - output_field=IntegerField(), - ) - ), - ).aggregate( + this_team_subquery = Subquery( + MatchParticipant.objects.filter(match_id=OuterRef("pk"), team_id=team_id) + .values("match_id") + .annotate(total_score=Sum("score")) + .values("total_score")[:1] + ) + + other_team_subquery = Subquery( + MatchParticipant.objects.filter(match_id=OuterRef("pk")) + .exclude(team_id=team_id) + .values("match_id") + .annotate(total_score=Sum("score")) + .values("total_score")[:1] + ) + + annotated_queryset = queryset.annotate( + this_team_score=this_team_subquery, other_team_score=other_team_subquery + ) + + results = annotated_queryset.aggregate( ranked_wins=Coalesce( Sum( Case(