gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:34:04 24 4
gpt4 key购买 nike

我想为 django admin 创建自定义过滤器,而不是普通的“is_staff”和“is_superuser”。我读过这个list_filter在 Django 文档中。自定义过滤器以这种方式工作:

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 编写新的自定义函数?欢迎任何建议或改进。需要一些指导......谢谢......

最佳答案

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

关于django - 在 Django Admin 中为 list_filter 创建自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12102697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com