Django QuerySet 按表达式排序
可能的重复:
django - 按计算字段排序查询集
我如何使用 order_by 像order_by('字段1'*'字段2') 例如,我有以不同货币列出价格的商品,因此要订购商品 - 我必须进行货币转换。
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 排序。
Possible Duplicate:
django - ordering queryset by a calculated field
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)
I would like to have something like:
Item.objects.all().order_by(F('priceRT')*F('cur__rateToUSD'))
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
extra()
方法。具体来说,select
参数用于指定方程,order_by
参数用于进行排序。Use the
extra()
method. Specifically theselect
argument to specify the equation, and theorder_by
argument to do the ordering.无聊的方法:向您的 Item 类添加一个名为 PriceUSD 的额外字段,并使用重写的 save 方法填充它。意味着您不必承担对每个查询运行计算的负担 - 只需在每个更新上运行计算即可。所以这是否好取决于你是否倾向于写更多或读更多(考虑到你的问题,也许它被读了?)
像这样:
在我的 django 东西中,每当我尝试实现聪明的计算字段如果不将它们存储在数据库中,我通常会发现它有太多的缺点而没有用处(例如无法查询它们,无法对它们进行排序)。因此,使用自定义保存方法在数据库中存储适当的字段是我通常的做法,并且它工作正常。你会需要更多的错误检查和其他东西。
Boring way: add an extra field to your Item class called priceUSD, and populate it with an overriden save method. means you don't have the burden of running calculations on every single query - just on every single update. so whether that's good or not will depend on whether you tend to write more or read more (given your question, maybe it's read?)
something like this:
In my django stuff, whenever I've tried to implement clever calculated fields without storing them in the database, I've usually found it comes with too many disadvantages to be usefult (eg can't query on them, can't sort on them). so storing a proper field in the DB with a custom save method is how I've usually done it, and it works ok. you'll want a bit more error-checking and stuff tho.