Django admin - sorting list_filter

2019-03-23 11:42发布

enter image description here

I have 'version' in list_filter, and I want the latest version be after 'All' list item. In this case, how do I sort the list descending? (All, 3.6.99.108,3.6.99.107...)

1条回答
你好瞎i
2楼-- · 2019-03-23 12:39

Define default ordering in model Meta class:

class MyModel(models.Model):
    # some model fields here
    class Meta:
        ordering = ['-version',]

If somehow it does not fulfill your purpose you can write your own custom list filter:

from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter

class VersionFilter(SimpleListFilter):
    title = _('version')

    parameter_name = 'version'

    def lookups(self, request, model_admin):
        qs = model_admin.queryset(request)
        return [(i, i) for i in qs.values_list('version', flat=True) \
                                  .distinct().order_by('-version')]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(version__exact=self.value())

class MyModel(ModelAdmin):
    list_filter = (VersionFilter,)

If you get following error AttributeError: object has no attribute 'queryset' then you are probably using Django 1.5+ use .get_queryset() instead e.g.

qs = model_admin.get_queryset(request)
查看更多
登录 后发表回答