如何按django中的计算值排序

时间:2009-05-30 23:34:21

标签: python django web-applications sorting django-models

嘿我想根据django中的计算值对对象进行排序...我该怎么做?

以下是基于堆栈溢出的用户配置文件模型示例,解释了我的困境:

class Profile(models.Model):
    user = models.ForeignKey(User)

    def get_reputation():
        ... 
        return reputation
    reputation = property(get_reputation)

所以,说我想按声誉对用户进行排序。我怎么做?我知道你不能这样做:

Profile.objects.order_by("-reputation")

感谢大家的帮助:)。

3 个答案:

答案 0 :(得分:16)

由于您的计算代码仅存在于Python中,因此您还必须在Python中执行排序:

sorted (Profile.objects.all (), key = lambda p: p.reputation)

答案 1 :(得分:6)

从Django-1.8开始,只要计算出的值可以在SQL中呈现,就可以使用query expressions对QuerySet进行排序。您还可以将annotations用作模型order_by

from django.db.models import F
Profile.objects.annotate(reputation=(F('<field>') + ...)).order_by("-reputation")

+-*/**等基本操作可与F()一起使用。此外还有其他一些功能,例如CountAvgMax,...

链接:

另见SO Q&amp; A:Order a QuerySet by aggregate field value

答案 2 :(得分:4)

如果你需要在数据库中进行排序(因为你有很多记录,并且需要对它们进行分页),唯一真正的选择是将声誉转换为非规范化字段(例如在被覆盖的{{1}中更新模型上的方法)。