Home > Software design >  How can i convert string to int and then sort view by int value?
How can i convert string to int and then sort view by int value?

Time:02-19

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'

CodePudding user response:

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

  • Related