xadmin 自定义过滤器选项

默认过滤器会把所有的店铺都显示出来,如果店铺很多筛选会很不方便。我希望可以根据每个用户的权限不同来显示他们店铺

1.找到过滤器源码修改

地址:xadmin/filters.py

# 这是ForeignKey过滤字段的处理类,其他字段可能不是这个类
@manager.register
class RelatedFieldListFilter(ListFieldFilter):

    @classmethod
    def test(cls, field, request, params, model, admin_view, field_path):
        return is_related_field2(field)

    def __init__(self, field, request, params, model, model_admin, field_path):
        other_model = get_model_from_relation(field)
        if hasattr(field, 'remote_field'):
            rel_name = field.remote_field.get_related_field().name
        else:
            rel_name = other_model._meta.pk.name

        self.lookup_formats = {'in': '%%s__%s__in' % rel_name, 'exact': '%%s__%s__exact' %
                                                                        rel_name, 'isnull': '%s__isnull'}
        # 添加这一段代码
        if hasattr(model_admin,'{field}_choices'.format(field=field.name)):
            self.lookup_choices = getattr(model_admin,'{field}_choices'.format(field=field.name))(field, request, params, model, model_admin, field_path)
        else:
            self.lookup_choices = field.get_choices(include_blank=False)
        # 添加结束
        super(RelatedFieldListFilter, self).__init__(
            field, request, params, model, model_admin, field_path)

        if hasattr(field, 'verbose_name'):
            self.lookup_title = field.verbose_name
        else:
            self.lookup_title = other_model._meta.verbose_name
        self.title = self.lookup_title

2.在ModelAdmin中添加方法

    def store_choices(self, field, request, params, model, model_admin, field_path):
        
        # 如果是超级用户不做控制
        if self.request.user.is_superuser:
            return field.get_choices(include_blank=False)

        # 这里就是自己写条件,从数据库中查询出需要显示的店铺
        store_lst = self.get_query_set(model.objects).values('store__title').distinct().order_by('store__title')
        # 返回格式 [('pk','标题'),]
        return list(((store.get('store__title'), store.get('store__title')) for store in store_lst))

 

posted on 2020-04-15 14:26  信奉上帝的小和尚  阅读(1225)  评论(0编辑  收藏  举报

导航