【发布时间】:2021-01-21 19:21:09
【问题描述】:
我正在尝试通过“排名值”对我的查询集进行排序,该值在我的 django 模型中作为十进制字段具有,但是似乎“order_by”函数似乎不起作用?我的查询集总是一样的,没有排序。
我已经尝试了谷歌,但结果很短,我在这里遗漏了什么吗?
【问题讨论】:
标签: python django web web-applications
我正在尝试通过“排名值”对我的查询集进行排序,该值在我的 django 模型中作为十进制字段具有,但是似乎“order_by”函数似乎不起作用?我的查询集总是一样的,没有排序。
我已经尝试了谷歌,但结果很短,我在这里遗漏了什么吗?
【问题讨论】:
标签: python django web web-applications
这是因为DecimalField 在索引时存储为字符串。
假设你有
class My_model(models.Model):
n_decimals = 2
...
decimal_field = models.DecimalField(max_digits=10, decimal_places=n_decimals)
def temp_int_field(self, obj):
return int ( float(obj.decimal_field) * (10**n_decimals) ) # please notice that the exponent of 10 is equal to the number of decimal_places
尝试像这样进行 order_by:
query_set = My_model.objects.all().order_by('temp_int_field')
【讨论】:
我需要查看您的代码,但无需查看,我可以要求您对所有值使用“round(x)”函数(其中 x 是浮点数),它不会改变排名(数学上确定这一点),并且 order_by 将起作用
真的很想看看你的代码!
提示:使用 for 循环对所有数字进行四舍五入或创建函数
【讨论】: