django对计算模型字段进行排序 - 我可以使用.extra吗?

时间:2014-09-09 19:04:05

标签: django django-models

我有下面的模型。我想通过percent_vote订购。我知道我可以计算出值并保存到模型中的新字段,但我不想这样做。有没有办法使用.extra方法来做到这一点?

Django 1.6,sqlite3

class HallOfFame(models.Model):
    player = models.ForeignKey(Master)
    year = models.IntegerField(db_index=True)
    voted_by = models.CharField(max_length=30)
    ballots_cast = models.IntegerField()
    votes_needed = models.IntegerField()
    votes_received = models.IntegerField(db_index=True)
    inducted = models.BooleanField(db_index=True)
    category = models.CharField(max_length=30, db_index=True)
    needed_note = models.CharField(max_length=75, blank=True, null=True)


    def __unicode__(self):
        return "%s %s" % (self.player.name_first, self.player.name_last) 

    def percent_vote(self):
        try:
            return self.votes_received/float(self.ballots_cast)
        except ZeroDivisionError:
            return 0

2 个答案:

答案 0 :(得分:0)

是的,似乎你可以做这样的事情,但这可能取决于你的数据库后端(这应该适用于PostgreSQL):

q = HallOfFame.objects.extra(select={'percent_vote_integer': "votes_received/ballots_cast", 'percent_vote_remainder': "votes_received%ballots_cast"})
q = q.extra(order_by = ['percent_vote_integer', percent_vote_remainder])

答案 1 :(得分:0)

我最终用下面的代码解决了这个问题。 @Emil Davtyan的答案对我没有用,我想找出一个更通用的解决方案。

def home(request):
    hall =  HallOfFame.objects.filter(inducted=True, voted_by='BBWAA')  
    hall_sorted = sorted(hall, key=lambda member: member.percent_vote, reverse=True)[:20]
    return render_to_response('top_lists.html', {'hall': hall_sorted })

模型有这个:

   @property
    def percent_vote(self):
        try:
            return float(self.votes_received)/self.ballots_cast

        except ZeroDivisionError:
            return 0