璃木Django基础学习

django admin列表页面, 右侧筛选框实现多选功能

2016-11-08  本文已影响183人  lidongchao

内容如题, 但是切记admin页面请勿定制得过于复杂. 复杂页面请自行设计

理念: 将url中的'='替换为'__in='

1 在根目录下, 新建一个文件夹 extraadminfilters, 在这个文件夹下新增两个文件__init__.py, 声明这个文件夹是一个; 'filters.py', 写我们的额外的Filter
filters.py代码如下

from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.filters import FieldListFilter
from django.db.models.fields import IntegerField, AutoField

class MultipleSelectFieldListFilter(FieldListFilter):

    def __init__(self, field, request, params, model, model_admin, field_path):
        self.lookup_kwarg = '%s_filter' % field_path
        self.filter_statement = '%s__id' % field_path
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
        self.lookup_choices = field.get_choices(include_blank=False)
        super(MultipleSelectFieldListFilter, self).__init__(
            field, request, params, model, model_admin, field_path)

    def expected_parameters(self):
        return [self.lookup_kwarg]

    def values(self):
        """
        Returns a list of values to filter on.
        """
        values = []
        value = self.used_parameters.get(self.lookup_kwarg, None)
        if value:
            values = value.split(',')
        # convert to integers if IntegerField
        if type(self.field.model._meta.pk) in [IntegerField, AutoField]:
            values = [int(x) for x in values]
        return values

    def queryset(self, request, queryset):
        raise NotImplementedError

    def choices(self, cl):
        # from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        yield {
            'selected': self.lookup_val is None,
            'query_string': cl.get_query_string({},
                [self.lookup_kwarg]),
            'display': _('All')
        }
        for pk_val, val in self.lookup_choices:
            selected = pk_val in self.values()
            pk_list = set(self.values())
            if selected:
                pk_list.remove(pk_val)
            else:
                pk_list.add(pk_val)
            queryset_value = ','.join([str(x) for x in pk_list])
            if pk_list:
                query_string = cl.get_query_string({
                    self.lookup_kwarg: queryset_value,
                    })
            else:
                query_string = cl.get_query_string({}, [self.lookup_kwarg])
            yield {
                'selected': selected,
                'query_string': query_string,
                'display': val,
            }


class IntersectionFieldListFilter(MultipleSelectFieldListFilter):
    """
    A FieldListFilter which allows multiple selection of
    filters for many-to-many type fields. A list of objects will be
    returned whose m2m contains all the selected filters.
    """

    def queryset(self, request, queryset):
        for value in self.values():
            filter_dct = {
                self.filter_statement: value
            }
            queryset = queryset.filter(**filter_dct)
        return queryset


class UnionFieldListFilter(MultipleSelectFieldListFilter):
    """
    A FieldListFilter which allows multiple selection of
    filters for many-to-many type fields. A list of objects will be
    returned whose m2m contains all the selected filters.
    """

    def queryset(self, request, queryset):
        filter_statement = "%s__in" % self.filter_statement
        filter_statement = filter_statement.replace('__id', '')
        filter_values = self.values()
        filter_dct = {
            filter_statement: filter_values
        }

        if filter_values:
            return queryset.filter(**filter_dct)
        else:
            return queryset

2 在需要使用多选的app对应的admin.py文件中, 引入刚刚新增的Filter
from extraadminfilters.filters import UnionFieldListFilter

3 在需要进行多重筛选的model对应adminlist_filter中进行修改成如下样式

list_filter的元素可以是单个的字段, 也能是一个包含两个元素的元组, 其中元组的的一个元素是字段名称, 第二是应用的Filter类

list_filter = (
        'creater',
        'status',
        ('shipping', UnionFieldListFilter),
        'group',
    )

此时, admin页面中已经可以进行多个筛选了, 再选择一次即可取消

Paste_Image.png
上一篇下一篇

猜你喜欢

热点阅读