Login

Tag "orderby"

2 snippets

Snippet List

Sophisticated order_by sorting

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
Read More

order_by template filter

put this code into a file in a folder "templatetags" inside some application and use it like this: {% load your_file_name %} {% for item in your_list|order_by:"field1,-field2,other_class__field_name"

  • template
  • filter
  • orderby
Read More