Django admin - sorting list_filter

后端 未结 1 475
挽巷
挽巷 2021-02-07 01:57

\"enter

I have \'version\' in list_filter, and I want the latest version be after \'All\'

1条回答
  •  迷失自我
    2021-02-07 02:08

    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)
    

    0 讨论(0)
提交回复
热议问题