Django Admin Column Sort Descending

白昼怎懂夜的黑 提交于 2019-12-11 01:35:55

问题


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:


回答1:


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



来源:https://stackoverflow.com/questions/12910281/django-admin-column-sort-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!