user9192656
user9192656

Reputation: 579

Filter only by years in django admin

I would like to create a filter in the admin panel which would filter events based on the year. I've created a list of years, but I do not know how to combine it with lookup and queryset.

class SearchByYear(admin.SimpleListFilter):
    title = _('title')
    parameter_name = 'year'
    year_list = models.Event.objects.values_list('date', flat=True)

    y = [i.year for i in year_list]
    print('this is list only with years: ', y)

    def lookups(self, request, model_admin):
        return (
            ('year', _('2018')),
            ('year1', _('2019')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'year':
            return queryset.filter(date__year=2018)
        if self.value() == 'year1':
            return queryset.filter(date__year=2019)

Upvotes: 3

Views: 604

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

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.

Upvotes: 5

Related Questions