Django: ordering numerical value with order_by

前端 未结 8 1929
陌清茗
陌清茗 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:45

    If you're using PostgreSQL (not sure about MySQL) you can safely use following code on char/text fields and avoid cast errors:

    MyModel.objects.extra(
        select={'myinteger': "CAST(substring(charfield FROM '^[0-9]+') AS INTEGER)"}
    ).order_by('myinteger')
    

提交回复
热议问题