Django: ordering numerical value with order_by

前端 未结 8 1928
陌清茗
陌清茗 2020-12-01 08:11

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 ordere

8条回答
  •  悲&欢浪女
    2020-12-01 08:37

    The problem you're up against is quite similar to how filenames get ordered when sorting by filename. There, you want "2 Foo.mp3" to appear before "12 Foo.mp3".

    A common approach is to "normalize" numbers to expanding to a fixed number of digits, and then sorting based on the normalized form. That is, for purposes of sorting, "2 Foo.mp3" might expand to "0000000002 Foo.mp3".

    Django won't help you here directly. You can either add a field to store the "normalized" address, and have the database order_by that, or you can do a custom sort in your view (or in a helper that your view uses) on address records before handing the list of records to a template.

提交回复
热议问题