如何通过派生计算对对象进行排序?

时间:2017-10-10 19:58:53

标签: python django django-rest-framework

我有一个名为Team的班级,有胜负。
我希望能够按win_pct对球队进行排序,这应该是胜利与比赛总数的比率(即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())

所以,在我看来,我有类似的东西:

@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
    )

但它只是出错:

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

1 个答案:

答案 0 :(得分:0)

尝试以下代码

from django.db.models import Count
teams = Team.objects.all().annotate(
    win_pct=(Count('wins')/(Count('wins')+Count('losses')))).order_by('win_pct')