Django: ordering numerical value with order_by

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

    I was looking for a way to sort the numeric chars in a CharField and my search led me here. The name fields in my objects are CC Licenses, e.g., 'CC BY-NC 4.0'.

    Since extra() is going to be deprecated, I was able to do it this way:

    MyObject.objects.all()
        .annotate(sorting_int=Cast(Func(F('name'), Value('\D'), Value(''), Value('g'), function='regexp_replace'), IntegerField()))
        .order_by('-sorting_int')
    

    Thus, MyObject with name='CC BY-NC 4.0' now has sorting_int=40.

提交回复
热议问题