简体   繁体   中英

Filtering the filters in Django Admin

Here is my code for a school project http://dpaste.com/434311/

The code works fine, on studentadmin list page, I get filter for classes which is good but as you can see my project is multi-tenant so in filter area I want to show only the classes for the school the current user is logged in (tracked thru sessions) but right now I can see list of all classes from all schools

so I want to replace this line

list_filter   = ['xclass']  

with something like

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

how can I do it ?

As of version 1.4 released March 23, 2012 you can use the official django.contrib.admin.SimpleListFilter

Here is an example of filter code used to that list active company only:

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())

I've run into this issue many times. Unfortunately, you are going to need to write a custom, undocumented FilterSpec .

Custom Filter in Django Admin on Django 1.3 or below

It's being worked on so should be here soon...
http://code.djangoproject.com/ticket/5833


An alternative is to modify the base queryset for the list page with only those from your school id. http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.queryset

def queryset(self, request):
    qs = super(MyModelAdmin, self).queryset(request)
    return qs.filter(xclass__school__id=request.session['school_id'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM