Django QuerySet 按表达式排序 [英] Django QuerySet ordering by expression
问题描述
可能的重复:
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屋!