0

I want sort view by a value that is string. but before that, i want convert string to int then sort by that.

main = models.Main.objects.all().order_by('fore_key__n')

In this code fore_key__n is string value like '20'

Darwin
  • 1,695
  • 1
  • 19
  • 29
  • 1
    You can use `ord()` and `chr()` to get the ASCII representation of a single charactor. So you can convert your string in a list of numbers, sort them and the convert back a string of characters. – OCP30pt1c1l1l43-X1z17 Feb 17 '22 at 12:52
  • Related: https://stackoverflow.com/questions/2969348/django-ordering-numerical-value-with-order-by – LaCharcaSoftware Feb 17 '22 at 13:00

1 Answers1

2

Annotations and DB functions can probably do this. Cast the string value to an int and then use it to order the queryset. I haven't ever had cause to try this, so treat the following as a suggestion:

 main = models.Main.objects.annotate(
   fkn_int_cast=Cast('fore_key__n', output_field=IntegerField()),
 ).order_by('fkn_int_cast')

It will throw a django.db.utils.DataError should the data in the field not be capable of conversion. Therefore, it's probably necessary to apply a regex filter as well

 main = models.Main.objects.filter(
   fore_key_n__regex='^[0-9]+$'
 ).annotate(
   fkn_int_cast=Cast('fore_key__n', output_field=IntegerField()),
 ).order_by('fkn_int_cast')

There are other DB functions you might use, for example, to replace the commas in '1,234,456' with null strings so it becomes Cast'able

nigel222
  • 7,582
  • 1
  • 14
  • 22