Django:用order_by排序数值 [英] Django: ordering numerical value with order_by

查看:960
本文介绍了Django:用order_by排序数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的问题是,显然这是一个情况,我必须通过CharField输出一个相当大的对象列表来存储街道地址。数据由ASCII码排序,因为它是一个Charfield,具有可预测的结果..它排序这样的数字;

  1, 10,11,12,13,14,15,16,17,18,19,2,20,21 .... 

现在明显的一步是改变Charfield的正确字段类型(IntegerField这个说法),但是由于某些地址可能会有公寓,所以它不能工作,如128A。



我真的不知道我可以如何正确地订购..

解决方案

如果您确定在该字段中只有整数,您可以通过 extra 方法获取数据库作为整数,并按以下顺序排列:

  MyModel.objects.extra(
select = {'myinteger':'CAST(mycharfield AS INTEGER)'}
).order_by('myinteger')


I'm in a situation where I must output a quite large list of objects by a CharField used to store street addresses.

My problem is, that obviously the data is ordered by ASCII codes since it's a Charfield, with the predictable results .. it sort the numbers like this;

1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21....

Now the obvious step would be to change the Charfield the proper field type (IntegerField let's say), however it cannot work since some address might have apartments .. like "128A".

I really don't know how I can order this properly ..

解决方案

If you're sure there are only integers in the field, you could get the database to cast it as an integer via the extra method, and order by that:

MyModel.objects.extra(
    select={'myinteger': 'CAST(mycharfield AS INTEGER)'}
).order_by('myinteger')

这篇关于Django:用order_by排序数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆