Django: ordering numerical value with order_by

前端 未结 8 1920
陌清茗
陌清茗 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')
    
    0 讨论(0)
  • 2020-12-01 08:48

    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')
    
    0 讨论(0)
提交回复
热议问题