Django QuerySet 按表达式排序 [英] Django QuerySet ordering by expression

查看:26
本文介绍了Django QuerySet 按表达式排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
django - 按计算字段对查询集进行排序

我如何像 order_by('field1'*'field2') 一样使用 order_by例如,我有以不同货币列出价格的商品,因此要订购商品 - 我必须进行货币换算.

How can i use order_by like order_by('field1'*'field2') For example i have items with price listed in different currencies, so to order items - i have to make currency conversion.

class Currency(models.Model):
    code    = models.CharField(max_length=3, primary_key=True) 
    rateToUSD   = models.DecimalField(max_digits=20,decimal_places=10)

class Item(models.Model):
    priceRT     = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    cur     = models.ForeignKey(Currency)

我想要类似的东西:

Item.objects.all().order_by(F('priceRT')*F('cur__rateToUSD'))

但不幸的是它不起作用,我的注释也失败了.我如何通过 2 个模型字段的值乘法结果来固定 QuerySet 排序.

But unfortunately it doesnt work, i also faild with annotate. How can i permorm QuerySet ordering by result of value multiplication of 2 model's fields.

推荐答案

使用 extra() 方法.特别是 select 参数指定方程,order_by 参数进行排序.

Use the extra() method. Specifically the select argument to specify the equation, and the order_by argument to do the ordering.

这篇关于Django QuerySet 按表达式排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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