Django: ordering numerical value with order_by

前端 未结 8 1932
陌清茗
陌清茗 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条回答
  •  旧时难觅i
    2020-12-01 08:35

    In my case i have a CharField with a name field, which has mixed (int+string) values, for example. "a1", "f65", "P", "55" e.t.c ..

    Solved the issue by using the sql cast (tested with postgres & mysql), first, I try to sort by the casted integer value, and then by the original value of the name field.

    parking_slots = ParkingSlot.objects.all().extra(
            select={'num_from_name': 'CAST(name AS INTEGER)'}
        ).order_by('num_from_name', 'name')
    

    This way, in any case, the correct sorting works for me.

提交回复
热议问题