1

如果传递了一个模型管理员,我想做一些事情,如果传递了另一个模型管理员,我想做另一件事。但似乎 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 作为参数包含在内来进行这些更改?需要一些指导...

4

1 回答 1

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,)
于 2012-08-27T09:13:41.217 回答