如何通过django中的计算值进行排序 [英] how to sort by a computed value in django

查看:128
本文介绍了如何通过django中的计算值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是一个基于堆栈的用户配置文件模型的例子溢出解释了我的困境:

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

def get_reputation():
...
返回信誉
名誉=属性(get_reputation)

所以说我想用信誉来排序用户。我怎么做?我知道你不能这样做:

  Profile.objects.order_by( -  reputation)

感谢您的帮助每个人:)

解决方案

如果您需要在数据库中进行排序(因为您有很多记录,并且需要对其进行分页),唯一真正的选择是将信誉转变为非规范化字段(例如,更新为覆盖 save()方法)。


Hey I want to sort objects based on a computed value in django... how do I do it?

Here is an example User profile model based on stack overflow that explains my predicament:

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

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

So, say I want to sort users by reputation. How do I do that? I know you can't just do this:

Profile.objects.order_by("-reputation")

Thanks for your help everyone :)

解决方案

If you need to do the sorting in the database (because you have lots of records, and need to e.g. paginate them), the only real option is to turn reputation into a denormalized field (e.g. updated in an overridden save() method on the model).

这篇关于如何通过django中的计算值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆