Home > front end >  Django admin: How to reverse the order of list_filter?
Django admin: How to reverse the order of list_filter?

Time:01-15

I have a dataset with models that show the year. What I need to do is reverse the order. By default, the Django admin interface shows the year by order of ascending number value (e.g. 2021, 2022, etc). What I'm aiming at is for the filter to display 2022, 2021.

models.py

...

def model(models.Model):
   year = models.IntegerField()

admin.py

...

class ModelAdmin(admin.ModelAdmin):
   list_filter = ("year")

I think this is a very trivial question, but I haven't found the solution yet. Thanks in advance.

CodePudding user response:

I suppose you can try to define default ordering in model Meta class:

class YourModel(models.Model):
    class Meta:
        ordering = ['-year', ]

If it does not work for you, the only option for you is to use custom filter like this:

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

class YearFilter(SimpleListFilter):
    title = _('year')

    parameter_name = 'year'

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

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

class ModelAdmin(admin.ModelAdmin):
    list_filter = (YearFilter,)

CodePudding user response:

you can just use order_by and reverse. for example some pattern like this:

records=yourmodel.objects.filter(x=y).order_by('year').reverse
  •  Tags:  
  • Related