xadmin choice filter 多选

  1. 在xadmin/filters.py中添加MultiSelectFieldListChoiceFilter
@manager.register
class MultiSelectFieldListChoiceFilter(MultiSelectFieldListFilter):
    def choices(self):
        self.lookup_in_val = (type(self.lookup_in_val) in (tuple, list)) and self.lookup_in_val or list(
            self.lookup_in_val)
        yield {
            'selected': len(self.lookup_in_val) == 0,
            'query_string': self.query_string({}, [self.lookup_in_name]),
            'display': _('All'),
        }
        # for val in self.lookup_choices:
        for lookup, val in self.field.flatchoices:
            yield {
                'selected': smart_text(lookup) in self.lookup_in_val,
                'query_string': self.query_string({self.lookup_in_name: ",".join([lookup] + self.lookup_in_val), }),
                'remove_query_string': self.query_string(
                    {self.lookup_in_name: ",".join([v for v in self.lookup_in_val if v != val]), }),
                'display': val,
            }
  1. 在xadmin.py中
def get_filter_fields(cls):
    return [(i.attname.replace('_id', ''), MultiSelectFieldListChoiceFilter) if i.choices else i.attname.replace('_id', '')
            for i in cls._meta.fields if not i.attname.startswith('_')]

class TestAdmin:
    list_filter = get_filter_fields(Test)

xadmin.site.register(Test, TestAdmin)
posted @ 2021-06-17 09:57  twfb  阅读(175)  评论(0编辑  收藏  举报