Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering query result by numeric strings in django (postgres backend)

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?

like image 769
yilmazhuseyin Avatar asked Jan 20 '12 13:01

yilmazhuseyin


1 Answers

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'])
like image 144
Daniel Roseman Avatar answered Oct 17 '22 13:10

Daniel Roseman