Django, SQLite, GLOB, CAST and sorting
Some days ago I found an interesting dilemma while working on a django based application. The application has a model similar to this one:
class Customer(models.Model): code = models.CharField(_('Customer code'), max_length=10) joined = models.DateField(_('Joined date'), auto_now_add=True) first_name = models.CharField(_('First name'), max_length=255) last_name = models.CharField(_('First name'), max_length=255) email = models.EmailField(_('Email address')) ...
That code attribute is a CharField where alphanumeric customer codes are stored. Those codes are mostly numbers (1,2,3...N) but then there are also codes like 2a, 3-groupB, etc.
from .models import Customer customers = Customer.objects.all().order_by('code')
Or, if you want the results sorted in descending order:
customers = Customer.objects.all().order_by('-code')
But then, this was not an IntegerField, but a CharField, which means that using order_by would return something like:
0 1 10 11 12 13 ... 2 20 21 ... 3 ...
And so on. Not exactly what was needed.
The following is the write-up covering the little adventure that was the work to fix it.Continue reading "Django, SQLite, GLOB, CAST and sorting"