简体   繁体   English

Django order_by 字段总和

[英]Django order_by sum of fields

Is it possible to use the django ORM to order a queryset by the sum of two different fields?是否可以使用 django ORM 通过两个不同字段的总和来订购查询集?

For example, I have a model that looks like this:例如,我有一个看起来像这样的 model:

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'.但不幸的是,F 对象似乎不适用于“order_by”。 Is such a thing possible with django? django 有可能吗?

You can use extra for this. 你可以使用extra的。

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

See the documentation . 请参阅文档

I think it's time to provide better answer. 我认为是时候提供更好的答案了。 Since django team is considering deprecating extra() , it's better to use annotate() with F() expression: 由于django团队正在考虑弃用extra() ,因此最好使用带有F()表达式的annotate()

from django.db.models import F

Component.objects.annotate(fieldsum=F('material_cost') + F('labor_cost')).order_by('fieldsum')

see also https://code.djangoproject.com/ticket/25676 另见https://code.djangoproject.com/ticket/25676

Use extra: 额外使用:

Component.objects.extra(select = {'total_cost' : 'material_cost + labor_cost'},
                                   order_by = ['total_cost',])[0]

You can use F() expression directly in order_by now, your suggested code should work:您现在可以直接在order_by中使用F()表达式,您建议的代码应该可以工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM