I have a table with a name (varchar) field that only holds numeric string and I want to order my queries by this field. But name fields are being ordered by alphabetically but I want them to be ordered numerically. For instance if I get 1 2 200 100 as name fields values, It is being ordered like 1 100 2 200 but I need them to be 1 2 100 200.
I could be able to come up with following row query
select *
from my_table as t
where t.foo='bar'
order by cast(t.name as integer);
But cannot represent this as django orm querysets? is there any way to do that?
I'd ask first of all why you have a varchar column that needs to be treated as numeric, but never mind.
You can use the extra
queryset method to convert your string:
MyTable.objects.extra(select={'int_name': 'CAST(t.name AS INTEGER)'},
order_by=['int_name'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With