Django Admin Column Sort Descending

时间:2012-10-16 08:17:01

标签: django django-admin django-grappelli

当使用带有grappelli的Django管理员时,我希望点击列标题将按降序对表进行排序。

(我不希望通过在模型元类中定义排序字段来对列进行默认排序。)

默认行为是升序。

第一次点击应按以下顺序排列:

required behavior

1 个答案:

答案 0 :(得分:1)

重写def result_headers(cl)

添加以下两行:

    .....
    .....
    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
    ...
    ...

现在在ModelAdmin中你可以:

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

我测试了它并且有效