如果传递了一个modeladmin,我想做一些事情,如果传递了另一个modeladmin,我会做另一件事。但似乎modeladmin不会作为list_filter中的参数传递,而它会在django admin中的操作中传递。为什么会这样呢?
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))
例如,在上面的例子中,如果是一个要检查生日是在90年代或2000年之间的学生,我想做一些不同的事情。但它是父母,我想检查生日是在70年代还是80年代?假设将传递不同的modeladmin。我如何包含modeladmin作为参数来进行这些更改?需要一些指导......
答案 0 :(得分:3)
您可以设置self.model_admin:
class DecadeBornListFilter(SimpleListFilter):
#[...]
def lookups(self, request, model_admin):
self.model_admin = model_admin
# ...
def queryset(self, request, queryset):
# here you can use self.model_admin
或者,使用继承:
class BaseDecadeBornListFilter(SimpleListFilter):
# [...]
class DecadeBornListFilter1(BaseDecadeBornListFilter):
# [...]
class DecadeBornListFilter2(BaseDecadeBornListFilter):
# [...]
class StudentModelAdmin1(admin.ModelAdmin):
list_filter = (DecadeBornListFilter1,)
class StudentModelAdmin2(admin.ModelAdmin):
list_filter = (DecadeBornListFilter2,)