Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by split string django orm

I have an ID as a reference number and year in this format:

1/17
98/15
2/17
112/17
2345/17
67/17
9/17
8974/16

When i get my IDs out using django orm:

obj = MyIDs.objects.filter(run='run_1').order_by('ID')

I get them out in the order of the first number:

1/17
112/17
2/17
2345/17
67/17
8974/16
9/17
98/15

However as the number after the / is the year, I would like to order them by the year then number. I am able to do this easily in mySQL (using substring index etc) and also if it was a python list, but as I am now wanting to not process my objects before sending them to my html template - is there a way to do this in the orm?

like image 297
trouselife Avatar asked Nov 21 '25 05:11

trouselife


1 Answers

Django 2.0 is currently in alpha stage, but it has the StrIndex function that will probably be helpful. I haven't tested this, but it is a draft of what you can do. The slash will remain in the string, but since you're just sorting it, I don't think it will be a problem for you.

MyIDs.objects.filter(run='run_1').annotate(
    slash_pos=StrIndex(F('id'), '/')
).annotate(
    y=Substr(F('id'), F('slash_pos'))
).order_by('y', 'id')
like image 62
Bobort Avatar answered Nov 22 '25 17:11

Bobort



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!