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

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

问题描述

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

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")

感谢大家的帮助:)

推荐答案

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

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天全站免登陆