2017-10-10 172 views
1

我有一個名爲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 

回答

0

試試下面的代碼

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