在Django Admin中过滤过滤器

时间:2011-02-19 21:08:24

标签: python django django-admin

这是我的学校项目代码 http://dpaste.com/434311/

代码工作正常,在studentadmin列表页面上,我得到了类的过滤器 这是好的,但你可以看到我的项目是多租户,所以在过滤器 区域我想只显示当前用户所在学校的课程 登录(通过会话跟踪)但现在我可以看到所有列表 所有学校的课程

所以我想替换这一行

list_filter   = ['xclass']  

类似

list_filter   = Class.objects.filter(school=request.session['school_id'])

我该怎么办?

2 个答案:

答案 0 :(得分:2)

自2012年3月23日发布的1.4版本起,您可以使用官方django.contrib.admin.SimpleListFilter

以下是仅用于列出活动公司的过滤器代码的示例:

class ActiveCompaniesFilter(SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('active companies')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'project__company'

    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.
        """
        lookup_list = Company.objects.active().values_list('id', 'name').distinct()
        # 'objects.active' is a custom Company manager and is 
        # equivalent to filter 'objects.filter(status=100)'  
        return lookup_list

    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 'other')
        # to decide how to filter the queryset.
        if self.value():
            return queryset.filter(project__company=self.value())

答案 1 :(得分:1)

我多次遇到过这个问题。不幸的是,您将需要编写一个自定义的,未记录的FilterSpec

Custom Filter in Django Admin on Django 1.3 or below

它正在进行中所以应该很快就会在这里...
http://code.djangoproject.com/ticket/5833


另一种方法是修改列表页面的基础queryset,只包含您学校ID的基础def queryset(self, request): qs = super(MyModelAdmin, self).queryset(request) return qs.filter(xclass__school__id=request.session['school_id']) http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.queryset

{{1}}
相关问题