当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Django ModelAdmin.list_filter用法及代码示例


本文介绍 django.contrib.admin.ModelAdmin.list_filter 的用法。

声明

ModelAdmin.list_filter

设置list_filter以激活管理员更改列表页面右侧栏中的过滤器,如下图所示:

list_filter.png

list_filter 应该是元素的列表或元组,其中每个元素应该是以下类型之一:

  • 字段名称,其中指定的字段应为 BooleanFieldCharFieldDateFieldDateTimeFieldIntegerFieldForeignKeyManyToManyField ,例如:

    class PersonAdmin(admin.ModelAdmin):
        list_filter = ('is_staff', 'company')

    list_filter 中的字段名称也可以使用 __ 查找跨越关系,例如:

    class PersonAdmin(admin.UserAdmin):
        list_filter = ('company__name',)
  • 继承自 django.contrib.admin.SimpleListFilter 的类,您需要提供 titleparameter_name 属性并覆盖 lookupsqueryset 方法,例如:

    from datetime import date
    
    from django.contrib import admin
    from django.utils.translation import gettext_lazy as _
    
    class DecadeBornListFilter(admin.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 '90s')
            # 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(admin.ModelAdmin):
        list_filter = (DecadeBornListFilter,)

    注意

    为方便起见,HttpRequest 对象被传递给 lookupsqueryset 方法,例如:

    class AuthDecadeBornListFilter(DecadeBornListFilter):
    
        def lookups(self, request, model_admin):
            if request.user.is_superuser:
                return super().lookups(request, model_admin)
    
        def queryset(self, request, queryset):
            if request.user.is_superuser:
                return super().queryset(request, queryset)

    同样为方便起见,ModelAdmin 对象被传递给 lookups 方法,例如,如果您想基于可用数据进行查找:

    class AdvancedDecadeBornListFilter(DecadeBornListFilter):
    
        def lookups(self, request, model_admin):
            """
            Only show the lookups if there actually is
            anyone born in the corresponding decades.
            """
            qs = model_admin.get_queryset(request)
            if qs.filter(birthday__gte=date(1980, 1, 1),
                          birthday__lte=date(1989, 12, 31)).exists():
                yield ('80s', _('in the eighties'))
            if qs.filter(birthday__gte=date(1990, 1, 1),
                          birthday__lte=date(1999, 12, 31)).exists():
                yield ('90s', _('in the nineties'))
  • 一个元组,其中第一个元素是字段名,第二个元素是继承自 django.contrib.admin.FieldListFilter 的类,例如:

    class PersonAdmin(admin.ModelAdmin):
        list_filter = (
            ('is_staff', admin.BooleanFieldListFilter),
        )

    您可以使用 RelatedOnlyFieldListFilter 将相关模型的选择限制为该关系中涉及的对象:

    class BookAdmin(admin.ModelAdmin):
        list_filter = (
            ('author', admin.RelatedOnlyFieldListFilter),
        )

    假设 authorForeignKeyUser 模型,这会将 list_filter 选项限制为已写书的用户,而不是列出所有用户。

    您可以使用 EmptyFieldListFilter 过滤空值,它可以过滤空字符串和空值,具体取决于字段允许存储的内容:

    class BookAdmin(admin.ModelAdmin):
        list_filter = (
            ('title', admin.EmptyFieldListFilter),
        )

    注意

    FieldListFilter API 被认为是内部的,可能会被更改。

    注意

    不支持 GenericForeignKey 字段。

列表过滤器通常仅在过滤器有多个选择时才会出现。过滤器的has_output() 方法控制它是否出现。

可以指定用于呈现列表过滤器的自定义模板:

class FilterWithCustomTemplate(admin.SimpleListFilter):
    template = "custom_template.html"

有关具体示例,请参见 Django (admin/filter.html) 提供的默认模板。

相关用法


注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.contrib.admin.ModelAdmin.list_filter。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。