0

How do you make Django admin site to strictly sort by values alphabetically when column headers are clicked? column2 below is a foreignkey.

MyAdmin(admin.ModelAdmin):
    list_display = ('column1', 'column2')

Here column2 header when clicked should sort the change list alphabetically but is not?

column2
b
a
c

or 

column2
c
a
b

is the output.

komodoedit
  • 699
  • 2
  • 6
  • 10

2 Answers2

1

The information you provided (up to this moment) is not enough to give you a straight answer. However based on what you say, I suspect the problem you are facing is the following:

Django Admin sorts the "Strings" alphabetically (asc or desc depending of the current state), but when the column is a foreign-key it sorts by the id, even though it is displaying a "String" that you specified by the __str__(self): method on your model.

Since the sorting is done at the database, based on my knowledge you will not be able to do it, without editing the queryset (check this answer to see an example: How to allow sorting in the Django admin by a custom list_display field, which doesn't have a DB field nor annotatable).

dethos
  • 3,336
  • 1
  • 15
  • 15
0

This should be the default behaviour. Perhaps you have clicked on another column header before and then it adds column2 as the second ordering parameter? You can check the admin URL and see what ordering parameters are given (and if you don't know how to make sense of the URL, you can paste it here as well).

The other version I can think of is that the rows values are not in fact a, b and c, but some unicode stuff that isn't ordered correctly by default (i.e. usually a, b, ä are usually by default sorted a, ä, b when in fact in Estonian alphabet the first ordering is the correct one). To solve this problem, checkout the collation options on Django models.

wanaryytel
  • 3,352
  • 2
  • 18
  • 26