Last active
November 20, 2022 17:19
-
-
Save mailtodanish/25116060561d7e21689f0fc7e2e891d2 to your computer and use it in GitHub Desktop.
custom filter in admin.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date | |
from django.contrib import admin | |
from .models import Question | |
from django.utils.translation import gettext_lazy as _ | |
class CustomListFilter(admin.SimpleListFilter): | |
title = _('pub_date') | |
parameter_name = 'pubdate' | |
def lookups(self, request, model_admin): | |
return ( | |
('one_year_old', _('One Year old')), | |
('two_year_old', _('Two Years old')), | |
) | |
def queryset(self, request, queryset): | |
if self.value() == 'one_year_old': | |
return queryset.filter( | |
pub_date__gte=date(2021, 1, 1), | |
pub_date__lte=date(2022, 12, 31), | |
) | |
if self.value() == 'two_year_old': | |
return queryset.filter( | |
pub_date__gte=date(2020, 1, 1), | |
) | |
@admin.register(Question) | |
class QuestionAdmin(admin.ModelAdmin): | |
list_display = ( | |
'question_text', | |
'pub_date', | |
) | |
list_filter = ( CustomListFilter, | |
('isChoice', admin.BooleanFieldListFilter), | |
('question_text', admin.EmptyFieldListFilter), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment