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

w80xi6nr  于 2023-01-27  发布在  Go
关注(0)|答案(4)|浏览(220)

我想为django管理员定制过滤器,而不是普通的“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编写一个新的自定义函数吗?欢迎您提出任何建议或改进。需要一些指导...谢谢...

2cmtqfgy

2cmtqfgy1#

您确实可以通过扩展SimpleListFilter向管理员过滤器添加自定义过滤器。例如,如果您想向上面使用的国家/地区管理员过滤器添加"Africa"的洲过滤器,您可以执行以下操作:
在www.example.com中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,)
ldioqlga

ldioqlga2#

你的list_display,方法返回一个字符串,但是如果我理解正确的话,你想做的是添加一个过滤器,允许选择学生的国家,对吗?
对于这个简单的关系过滤器,实际上对于“Student-Country”列表显示列也是如此,您不需要创建自定义过滤器类,也不需要创建自定义列表显示方法;这就足够了:

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

django执行list_filter的方式,如文档中所解释的,首先是自动匹配你提供的字段到预先构建的过滤器类;这些过滤器包括字符字段和外键。
list_display同样使用通过检索相关对象并返回这些对象的unicode值(与上面提供的方法相同)传递的字段自动填充changelist列。

b4qexyjb

b4qexyjb3#

除了Rick Westera的答案,这里是DjangoDocs对于这种情况的说明

    • 一月一日**

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

e1xvtsh3

e1xvtsh34#

lookup函数用于显示admin中的现有值;在queryset函数中,self.value()是按..过滤的。

from django.contrib.admin import SimpleListFilter

class AllPriceFilter(admin.SimpleListFilter):

    title = 'All Price'
    parameter_name = 'All Price'

    def lookups(self, request, model_admin):
        return [(i.all_price, i.all_price) for i in model_admin.model.objects.all()]

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

class MyAdmin(admin.ModelAdmin):
    list_filter = (AllPriceFilter, )

相关问题