DjangoAdmin的自定义SimpleListFilter子类

2024-04-19 17:35:46 发布

您现在位置:Python中文网/ 问答频道 /正文

根据Django的文档,我需要一个SimpleListFilter子类,它与所描述的there非常相似:

from datetime import date

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

class DecadeBornListFilter(SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('decade born')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'decade'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('80s', _('in the eighties')),
            ('90s', _('in the nineties')),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or 'other')
        # to decide how to filter the queryset.
        if self.value() == '80s':
            return queryset.filter(birthday__gte=date(1980, 1, 1),
                                    birthday__lte=date(1989, 12, 31))
        if self.value() == '90s':
            return queryset.filter(birthday__gte=date(1990, 1, 1),
                                    birthday__lte=date(1999, 12, 31))

class PersonAdmin(ModelAdmin):
    list_filter = (DecadeBornListFilter,)

我需要做的唯一改变是在lookups方法中,而不是列出像80年代或90年代这样的几十年,我希望显示widgets来允许选择月份和年份,例如2000年1月。在

在最好的情况下,我想用两个下拉菜单,一个是年,另一个是月。另一种选择是重新使用日期范围,如DateRangeFilter,我尝试过,但无法创建继承DateRangeFilter或在新筛选器类的查找方法中使用DateRangeFilter的新筛选器类。在

我正在使用django1.7.8,任何帮助或提示都将非常感谢。在


Tags: theinfromimportselffordatethat
1条回答
网友
1楼 · 发布于 2024-04-19 17:35:46

您需要两个列表过滤器,一个用于最大日期,一个用于最小日期。查询所有不同年份的条目。像这样:

class MaxDateListFilter(SimpleListFilter):
    title = _('maximum date')
    parameter_name = 'max_date'

    def lookups(self, request, model_admin):
        return [(str(year.year), year.year) \
                 for year in Entry.objects.dates('pub_date', 'year')]

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

注意:未测试的代码。在

这对小范围有效。但是对于更大的数据集可能是不现实的。在

另一种方法是提供您自己的ModelAdmin.get_search_results并使其接受一些日期搜索查询。一旦你有了它,你需要渲染你自己的ModelAdmin.changelist\u视图. 将表单添加到上下文中,并自定义更改列表模板以呈现此表单。提交表单应生成正确的search GET请求。在

相关问题 更多 >