[Django]-Filter only by years in django admin

5๐Ÿ‘

โœ…

You can pass the years as options, and then use these when filtering:

from django.db.models.functions import ExtractYear

class SearchByYear(admin.SimpleListFilter):
    title = _('title')
    parameter_name = 'year'

    def lookups(self, request, model_admin):
        year_list = models.Event.objects.annotate(
            y=ExtractYear('date')
        ).order_by('y').values_list('y', flat=True).distinct()
        return [
            (str(y), _(str(y))) for y in year_list
        ]

    def queryset(self, request, queryset):
        if self.value() is not None:
            return queryset.filter(date__year=self.value())
        return queryset

We thus use the lookups to fetch the different years, later we then filter on the selected year, with a .filter(date__year=self.value()) query.

The translation _(str(y)) is not strictly necessary. It could be useful if years are translated differently in some cultures (for example Chinese/Japanese/Roman years). But there is usually no problem translating years, since if no translation is found, the translation will perform a โ€œfallbackโ€ to the original value.

Leave a comment