如何在django中通过模型函数进行排序

时间:2015-11-13 01:07:54

标签: python django django-models

我有以下型号:

class Player(models.Model):
    user = models.OneToOneField(User, related_name="player")
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)

    def point_total(self):
        playerAchievements = PlayerAchievement.objects.filter(player=self)
        score = 0
        for p in playerAchievements:
            score += p.achievement.value
        return score

    def full_name(self):
        return self.first_name + ' ' + self.last_name

    def rank(self):
        print '---'
        players = Player.objects.filter(team__league=self.team.league).order_by(self.point_total())
        print self.first_name
        position = 0
        for p in players:
            position +=1

            if p.id == self.id:
                return str(position)
        return '0'

此行没有处理任何内容:

players = Player.objects.filter(team__league=self.team.league).order_by(self.point_total())

我也试过这个但效果相同:

players = self.objects.filter(team__league=self.team.league).order_by('player__point_total')

如何通过点总函数进行排序,以便我可以计算每个玩家的等级?

2 个答案:

答案 0 :(得分:2)

order_by函数仅对数据库中的字段起作用,因此调用函数不会起作用。

你可以做的是annotate Count聚合ForeignKey然后order_by聚合的函数:

from django.db.models import Sum

players = Player.objects.filter(team__league=self.team.league)
players = players.annotate(achievement_sum=Sum('playerachievement_set__achievement__value'))
players = players.order_by('achievement_sum')

答案 1 :(得分:0)

您无法通过django中的方法和属性对查询集进行排序,您必须自己在python中进行排序。

players_to_sort = Player.objects.filter(team__league=self.team.league)
sorted_player = sorted(players_to_sort, key=lambda player: player.point_total() )