嘿我想根据django中的计算值对对象进行排序...我该怎么办?
以下是基于堆栈溢出的用户配置文件模型示例,解释了我的困境:
class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
Run Code Online (Sandbox Code Playgroud)
所以,说我想按声誉对用户进行排序.我怎么做?我知道你不能这样做:
Profile.objects.order_by("-reputation")
Run Code Online (Sandbox Code Playgroud)
谢谢大家的帮助 :)
可能的重复:
django - 按计算字段排序查询集
我如何使用 order_by 像 order_by('field1'*'field2') 例如,我有以不同货币列出价格的商品,因此要订购商品 - 我必须进行货币转换。
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)
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
Item.objects.all().order_by(F('priceRT')*F('cur__rateToUSD'))
Run Code Online (Sandbox Code Playgroud)
但不幸的是它不起作用,我的注释也失败了。我如何通过 2 个模型字段的值相乘的结果来执行 QuerySet 排序。