【问题标题】:Creating Custom Filters for list_filter in Django Admin在 Django Admin 中为 list_filter 创建自定义过滤器
【发布时间】:2012-08-19 14:56:03
【问题描述】:

我想为 django admin 制作自定义过滤器,而不是普通的 'is_staff' 和 'is_superuser'。我在 Django 文档中读过这个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,)

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

def Student_Country(self, obj):
    return '%s' % obj.country
Student_Country.short_description = 'Student-Country'

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

【问题讨论】:

标签: django django-admin


【解决方案1】:

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

对于这个简单的关系过滤器,实际上对于“Student-Country”列表显示栏也是如此,您不需要创建自定义过滤器类,也不需要创建自定义列表显示方法;这样就足够了:

class MyAdmin(admin.ModelAdmin):
    list_display = ('country', )
    list_filter = ('country', )

django 的方式list_filter,正如in the docs 解释的那样,首先是通过自动匹配您提供的字段到预先构建的过滤器类;这些过滤器包括 CharField 和 ForeignKey。

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

【讨论】:

    【解决方案2】:

    您确实可以通过扩展 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,)
    

    【讨论】:

    • 在查询集中它缺少默认的所有选择:如果 self.value() 为无:返回 queryset.all()
    • lookups 方法中的值被强制转换为字符串,因此请确保queryset 方法中的控制流检查字符串值,而不是整数或布尔字段等其他内容。
    • 最好使用.distinct() 而不是set
    • 如何从过滤器中删除“全部”选项
    【解决方案3】:

    除了Rick Westera 答案,这里是Django Docs 针对这种情况

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

    【讨论】:

    • 嗨哈希,我添加了您提供的链接的基本摘要。仅链接的答案不受欢迎,而且往往会被删除,因为链接可能会失效、更改等。答案应该是独立的,链接可以作为进一步的信息。
    猜你喜欢
    • 2012-10-18
    • 2019-07-11
    • 2011-07-09
    • 2011-10-17
    • 2018-06-25
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多