Skip to content

Commit

Permalink
calculate win/loss record without loops
Browse files Browse the repository at this point in the history
  • Loading branch information
apollo1291 authored and n8kim1 committed Jan 25, 2023
1 parent cd51e96 commit e359c10
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions backend/siarnaq/api/teams/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

import structlog
from django.db import transaction
from django.db.models import F, Max, Q
from django.shortcuts import get_object_or_404
from drf_spectacular.utils import extend_schema
from rest_framework import filters, mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from siarnaq.api.compete.models import MatchParticipant
from siarnaq.api.compete.models import Match
from siarnaq.api.episodes.permissions import IsEpisodeAvailable
from siarnaq.api.teams.exceptions import TeamMaxSizeExceeded
from siarnaq.api.teams.filters import TeamActiveSubmissionFilter, TeamOrderingFilter
Expand Down Expand Up @@ -183,26 +184,16 @@ def avatar(self, request, pk=None, *, episode_id):
)
def record(self, request, pk=None, *, episode_id):
"""Retrieve the win/loss record of a team"""
match_participations = MatchParticipant.objects.filter(
team_id=request.data["id"]
team = request.data["id"]
matches = Match.objects.filter(participants__team=team)

matches.annotate(
score_1=Max("participants__score", filter=Q(participants__team=team)),
score_2=Max("participants__score", filter=~Q(participants__team=team)),
)
win_count = 0
loss_count = 0
for mp in match_participations:
match = mp.match
team_score = [
p.score
for p in match.participants.all()
if p.team.id == request.data["id"]
]
opponent_score = [
p.score
for p in match.participants.all()
if p.team.id != request.data["id"]
]
if team_score and opponent_score:
if team_score[0] > opponent_score[0]:
win_count += 1
else:
loss_count += 1

win_count = matches.filter(score_1__gt=F("score_2")).count()

loss_count = matches.filter(score_1__lt=F("score_2")).count()

return Response({"wins": win_count, "losses": loss_count})

0 comments on commit e359c10

Please sign in to comment.