1

I have a class called Team that has wins and losses.
I want to be able to sort teams by a win_pct which should be the ratio of wins to total games played (i.e. wins.count()/(wins.count() + losses.count())).

class Team(TimestampModerated):
    name = models.CharField(max_length=80, blank=False, null=False)
    wins = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='related_wins')
    losses = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='related_losses')

    def num_wins(self):
        return self.wins.count()

    def num_losses(self):
        return self.losses.count()

    def win_pct(self):
        return self.wins.count()/(self.wins.count() + self.losses.count())

So, in my view I have something like this:

@list_route
def teams_list(self, request):
    teams = Team.objects.all().order_by('-win_pct')
    page = self.paginate_queryset(teams)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
    serializer = self.get_serializer(teams, many=True)
    return Response(
        data=serializer.data
    )

But it just gives an error:

django.core.exceptions.FieldError: Cannot resolve keyword 'win_pct' into a field. Choices are: created, id, losses, moderation_code, related_losses, related_wins, name, updated, wins
John Moutafis
  • 22,254
  • 11
  • 68
  • 112
Evan Zamir
  • 8,059
  • 14
  • 56
  • 83

1 Answers1

0

Try below code

from django.db.models import Count
teams = Team.objects.all().annotate(
    win_pct=(Count('wins')/(Count('wins')+Count('losses')))).order_by('win_pct')
Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41