Search code examples
djangodjango-admindjango-grappelli

Django Admin Column Sort Descending


When using Django admin with grappelli I would like that a click on a column header will sort the table by descending order.

(I don't want a default ordering to the columns by defining the ordering field in the Model Meta Class.)

The default behavior is Ascending.

The first click should order like this:

required behavior


Solution

  • Rewrite the def result_headers(cl)

    add these 2 lines:

        .....
        .....
        th_classes = ['sortable']
        order_type = ''
    
        #new lines
    
        default_order_type = getattr(attr, "admin_order_first_type", None)
        new_order_type = default_order_type if default_order_type else 'asc'
    
        #end of new lines
    
        sort_priority = 0
        sorted = False
        ...
        ...
    

    now in the ModelAdmin you can:

    list_display = ('number_of_players', ....)
    
    def number_of_players(self, team):
            return intcomma(team.number_of_players)
    
    number_of_players.short_description = '# num of players'
    number_of_players.admin_order_field = 'number_of_players'
    number_of_players.admin_order_first_type = 'desc' #will make the column to be ordered desc first
    

    I tested it and it works