django - 按计算字段排序查询 [英] django - ordering queryset by a calculated field

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

问题描述

我想要一个具有计算字段的模型,我可以应用排序。例如,假设我有以下模型:

I want to have a model with calculated fields that I can apply sorting on. For example, let's say that I have the following model:

class Foo(models.Model):
    A = models.IntegerField(..)
    B = models.IntegerField(..)
    C = models.ForeignKey(..)

我想要一个由以下公式计算的D和E字段:

I want to have a D and an E field that are calculated by the following formulas:


  1. D = A - B

  2. E = A - X(其中X是C型相关记录的一个字段)

如果我不需要应用排序,实现这一点将是微不足道的;我只是添加属性到模型类。然而,我需要这些字段的排序。

Implementing this would be trivial if I didn't need to apply sorting; I would just add properties to the model class. However, I need ordering by these fields.

一个解决方案是将所有记录都记录到内存中,然后进行排序,这是我最后设想的(它会打破事情有关分页)。

A solution is to fetch all records into memory and do the sorting there, which I conceive a last resort (it will break things regarding pagination).

有没有办法实现我正在尝试?任何指导都不胜感激。

Is there a way to achieve what I'm trying? Any guidance is appreciated.

编辑:字段X的值非常频繁地变化,并且大量的Foo记录与模型C的一个记录相关.X的更新将需要数以千计的E更新。

Denormalization is a no-go. The value of field X changes very frequently and a lot of Foo records are related to one record of model C. An update of X will require thousands of updates of E.

推荐答案

我将看看 extra 方法,并指定 order_by 参数。

这篇关于django - 按计算字段排序查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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