在Django Admin中为list_filter创建自定义过滤器

lak*_*esh 52 django django-admin

我想为django admin而不是普通的'is_staff'和'is_superuser'制作自定义过滤器.我在Django docs中读过这个list_filter.自定义过滤器以这种方式工作:

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 '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(ModelAdmin):
    list_filter = (DecadeBornListFilter,)
Run Code Online (Sandbox Code Playgroud)

但我已经为list_display制作了这样的自定义函数:

def Student_Country(self, obj):
    return '%s' % obj.country
Student_Country.short_description = 'Student-Country'
Run Code Online (Sandbox Code Playgroud)

有可能我可以在list_filter中使用list_display的自定义函数,而不是为list_filter编写新的自定义函数吗?欢迎任何建议或改进..需要一些指导......谢谢......

Ric*_*era 33

您确实可以通过扩展SimpleListFilter为管理过滤器添加自定义过滤器.例如,如果要将"非洲"的大陆过滤器添加到上面使用的国家/地区管理过滤器,则可以执行以下操作:

在admin.py中:

from django.contrib.admin import SimpleListFilter

class CountryFilter(SimpleListFilter):
    title = 'country' # or use _('country') for translated title
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        countries = set([c.country for c in model_admin.model.objects.all()])
        return [(c.id, c.name) for c in countries] + [
          ('AFRICA', 'AFRICA - ALL')]

    def queryset(self, request, queryset):
        if self.value() == 'AFRICA':
            return queryset.filter(country__continent='Africa')
        if self.value():
            return queryset.filter(country__id__exact=self.value())

class CityAdmin(ModelAdmin):
    list_filter = (CountryFilter,)
Run Code Online (Sandbox Code Playgroud)

  • 在查询集中缺少默认的所有选择:如果 self.value() 为 None: return queryset.all() (2认同)

tut*_*uju 6

您的list_display方法返回一个字符串,但是,如果我理解正确,那么您想要做的就是添加一个过滤器,该过滤器允许选择学生所在的国家/地区,对吗?

对于这种简单的关系过滤器,实际上对于“ Student-Country”列表显示列,您也无需创建自定义过滤器类或自定义列表显示方法。这样就足够了:

class MyAdmin(admin.ModelAdmin):
    list_display = ('country', )
    list_filter = ('country', )
Run Code Online (Sandbox Code Playgroud)

该办法Django的呢list_filter,因为解释的文档,最早是由您提供的预建过滤器类自动匹配字段; 这些过滤器包括CharField和ForeignKey。

list_display类似地,使用通过检索相关对象并返回这些对象的unicode值(与上面提供的方法相同)传递的字段来自动执行变更列表列的填充。


has*_*her 5

除了Rick Westera 的回答之外,这里还有针对这种情况的Django 文档

ModelAdmin.list_filter
设置list_filter为激活管理员更改列表页面右侧栏中的过滤器
list_filter应该是元素列表或元组

  • 嗨哈什尔,我添加了您提供的链接的基本摘要。仅链接的答案是不受欢迎的,并且往往会被删除,因为链接可能会消失、更改等。答案应该是独立的,链接可以作为进一步的信息。 (2认同)