Django's `floatformat` is a good way to format a number if you require a specific amount of decimals. It is, however, very slow. In testing each `floatformat` call took 200–250 us, which means it'll take a second to render a page that floatformats 4000 numbers.
Much of the time comes from using `Decimals`. I looked at using the `cdecimal` module, and while it improved the speed, each call still clocked in at between 80 and 100 us.
`fast_floatformat` is not locale aware, and doesn't look at Django settings for USE_THOUSAND_SEPARATOR, but it'll take between 1.2 and 3 us per call for ints, floats and strings, and about 12 us per call for Decimals, giving you up to 800000 floatformatted numbers per second.
I wanted to sort a CharField which consists of digits in a different way. This field is a matricle number field (some kind of registration number for students. They have matricle numbers in the format YYxxxxxx - which means "YY" are the last two digits of the year they started studying.)
So I wanted to sort them in a way that they appear like this:
5000000, 5000001, ... , 9999998, 9999999, 0000000, 0000001, ... , 1200000, ... , 4999999
Took me some time to find out how to do this efficiently in PostgreSQL, and so I thought I'd share it here.
The important stuff is in the model "Candidate" to use a special "objects" object manager which uses a special QuerySet as well. Here lies the "magic": If there is a ordering required that contains "mnr", then a special on-the-fly calculated field will be added to the queryset called "mnr_specialsorted".
Now it is possible to do things like
`Candidate.objects.filter( firstname__contains="Pony" ).exclude( lastname__contains="Java" ).order_by("lastname", "-mnr")`
For other database engines you might want to change the MNR_SORTER variable to fit your needs.
- sort
- orderby
- sorting
- ordering