Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin - sorting list_filter

Tags:

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

like image 785
Ron D. Avatar asked May 15 '13 08:05

Ron D.


1 Answers

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) 
like image 119
Aamir Rind Avatar answered Sep 28 '22 02:09

Aamir Rind