开发者

Django alphanumeric sort in order_by

My question is exactly like this one, except that it's a query returned in Django.

I want the fields returned b开发者_如何学运维y

text_all = RawText.objects.filter(id__contains=county.short_code).order_by('id')

to be returned as

1,1
2,1
10,1

rather than:

1,1
10,1
2,1

What can I do? N.B. ID is a char field, it has to be because of the commas.

Thanks!


If your id represents decimal number, you better have to use the right datatype in the database and decide to show the char ',' elsewhere (maybe by playing with internationalization).

Otherwise, you will have to write your own sorting method at application level after retrieving datas.


You could make your text field fixed length, so instead of

1,1
10,1
2,1

You'd have

001,1
002,1
010,1


First approach: have two extra numeric columns in your RawText model, first column will correspond to your first part of the the id and the second column would correspond to the second part of your id. That way the sort is trivial:

text_all = RawText.objects.filter(id__contains=county.short_code).order_by('first_part', 'second_part')

Alternative approach: have the sorting done in your application:

  1. Extract the two numeric portions of your ids
  2. Sort the queryset

Yet another approach: you can make your id instead of char to be a Decimal type, that way you can just sort it as numeric:

1.1
2.1
10.1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜