Skip to content

Commit

Permalink
fixing query in scrimmage record, win/loss/tie (#898)
Browse files Browse the repository at this point in the history
  • Loading branch information
nour-massri authored Jan 10, 2025
1 parent caf8eb9 commit bf84589
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions backend/siarnaq/api/compete/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
Q,
Subquery,
Sum,
Value,
When,
)
from django.db.models.functions import Coalesce
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit bf84589

Please sign in to comment.