[英]Sort QuerySet based on the higher of two different fields
I have this model: 我有这个模型:
class ScoringModel(model.Model):
red_score = models.SmallIntegerField()
blue_score = models.SmallIntegerField()
I'm trying to sort a query set based on whichever is greater between the two. 我正在尝试根据两者之间的较大者对查询集进行排序。 Now, taking the sum of them wouldn't work because that means a score of 90 to 0 would have a lower rank than a score of 50 to 50, which is not what I want.
现在,将它们加起来将不起作用,因为这意味着90到0的得分比50到50的得分更低,这不是我想要的。 (I'm trying to find a list of high scores, basically.)
(基本上,我正在尝试查找高分列表。)
I tried adding a function inside of the model, as such: 我尝试在模型内部添加一个函数,如下所示:
class ScoringModel(model.Model):
red_score = models.SmallIntegerField()
blue_score = models.SmallIntegerField()
def max_score(self):
return self.red_score if self.red_score > self.blue_score else self.blue_score
Which doesn't work, since the order_by
function doesn't support function return values (ie ScoringModel.objects.order_by('-max_score')
and ScoringModel.objects.order_by('-max_score()')
fail to run). 这不起作用,因为
order_by
函数不支持函数返回值(即ScoringModel.objects.order_by('-max_score')
和ScoringModel.objects.order_by('-max_score()')
无法运行)。
Any help would be very appreciated 任何帮助将不胜感激
I can suggest you to see this answer 我可以建议你看看这个答案
https://stackoverflow.com/a/1875616/5518973 https://stackoverflow.com/a/1875616/5518973
you can use mysql function GREATEST(field1, field2) instead of Sum and then order by that extra field. 您可以使用mysql函数GREATEST(field1,field2)代替Sum,然后按该额外字段排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.