Django order_by字段数 [英] Django order_by sum of fields

查看:145
本文介绍了Django order_by字段数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用django ORM按两个不同字段的总和来排序查询?



例如,我有一个如下所示的模型:

  class Component(models.Model):
material_cost = CostField()
labor_cost = CostField

我想这样做:

  component = Component.objects.order_by(F('material_cost')+ F('labor_cost'))[0] 
pre>

但不幸的是,F对象似乎不能与order_by一起使用。可以用django这样的事情吗?

解决方案

你可以使用 extra 为此。

  Component.objects.extra(
select = {'fieldsum':'material_cost + labor_cost'} ,
order_by =('fieldsum',)

请参阅文档


Is it possible to use the django ORM to order a queryset by the sum of two different fields?

For example, I have a model that looks like this:

class Component(models.Model):
    material_cost = CostField()
    labor_cost = CostField()

and I want to do something like this:

component = Component.objects.order_by(F('material_cost') + F('labor_cost'))[0]

But unfortunately, F objects don't seem to work with 'order_by'. Is such a thing possible with django?

解决方案

You can use extra for this.

Component.objects.extra(
    select={'fieldsum':'material_cost + labor_cost'},
    order_by=('fieldsum',)
)

See the documentation.

这篇关于Django order_by字段数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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