Search code examples
djangodjango-orm

Group Symbols Together during order_by


When using order_by in the Django ORM it seems that it is ignoring symbol characters in the text when sorting.

For example with the folowing query set.


+--------+
| name   |
+--------+
| 'A'    |
| '@B'   |
| 'C'    |
| 'D'    |
| '@E'   |
| 'F'    |
| '$G'   |
| '$H'   |
+--------+

When using Item.objects.all().order_by("name"), the list is returned exactly as you see above.

How do i order that list where the symbols are sorted together like so:

A,C,D,F,@B,@E,$G,$H


Solution

  • You can specify the collation using the Collate database function, for example:

    from django.db.models.functions import Collate
    
    ...
    items = Item.objects.order_by(Collate("name", "Latin1_General_CS_AI"))