當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。