django admin list_filter“或”条件

时间:2014-11-11 16:32:31

标签: python django filter django-admin django-admin-filters

抱歉,如果之前已经回答过这个问题,但我做了大量的谷歌搜索没有成功。

我知道如何在管理员视图中创建自定义list_filter(例如,继承SimpleFilter)。

我真正想要的是(在管理列表视图中)"检查"在OR公式中组合它们的不同过滤器。

举个例子,假设你有:

# models.py
class Foo(models.Model):
    foobar = ...
    foofie = ...
...

# admin.py
class FooAdmin(admin.ModelAdmin):
    list_filter = ( "foobar", "foofie" )
...

FooAdmin生成的管理列表视图中,我可以选择按foobarfoofie过滤记录。有没有办法按公式过滤它们:foobar = X OR foofie = Y,其中XYfoobarfoofie可以假设的两个值?

甚至可能吗?

我知道在django管理员视图中并非一切皆有可能,但这似乎是一个非常常见的请求,我想知道我是否错过理解或阅读的东西。

欢迎使用第三方应用程序。谢谢:))

4 个答案:

答案 0 :(得分:4)

我刚刚找到了第三方应用,django-advanced-filters符合您的要求。

它有:

  

OR字段

     

OR是添加到每个可用规则的​​附加字段   字段。

     

它允许使用OR语句构造查询。你可以使用它   创建一个“空”规则,该字段“介于”一组1或更多   规则。

我已经开始测试,添加OR field会有效。 这是截图: enter image description here

答案 1 :(得分:2)

首先,我尝试解释django管理过滤器的工作原理。当您想要在管理页面中过滤您的查询集时,django会查找所有已注册的过滤器。如果使用此值为filter django filter queryset设置值。如果你设置多个过滤器django过滤你的查询集两次,这等于queryset = queryset.filter(param1 = 1).filter(param2 = 2)或在SQL中:SELECT ... WHERE param1 = 1 AND param2 = 2。这是因为你无法使用标准的django过滤器。但你可以像这样编写自己的过滤器:

from django.contrib.admin import SimpleListFilter
from django.db.models import Q
from functools import reduce
import operator
from django.core.exceptions import FieldError


class ORListFilter(SimpleListFilter):
title = ''
parameter_name = ''
search_field = ('',)

def queryset(self, request, queryset):
    filters = request.GET.copy()
    try: #for search
        search_field_value = filters.pop('q')[0]
        query_params = [Q((key, search_field_value)) for key in self.search_field]
        try:
            queryset = queryset.filter(reduce(operator.or_, query_params))
        except FieldError:
            pass
    except KeyError:
        pass
    try:
        query_params = [Q((key, value)) for key, value in filters.dict().items()]
        queryset = queryset.filter(reduce(operator.or_, query_params))
    except TypeError:
        pass
    return queryset

def lookups(self, request, model_admin):
    qs = model_admin.get_queryset(request)
    parameters = qs.all().values(self.parameter_name).distinct()
    for parameter in parameters:
        value = dict(parameter).pop(self.parameter_name, None)
        if value:
            yield (value, value)
        else:
            yield (None, 'NULL')

class Field1Filter(ORListFilter):
    title = 'title'
    parameter_name = 'field1'
    search_field = ('search1', 'search2')


class Field2Filter(ORListFilter):
    title = 'title'
    parameter_name = 'field2'
    search_field = ('search1', 'search2')

并在admin:

中注册
search_fields = ('search1', 'search2')
list_filter = (Field1Filter, Field2Filter)

它不适用于标准的django过滤器,list_filter中的所有值都必须从ORListFilter类继承。此外,它不适用于日期时间过滤器,但您可以添加此功能。

答案 2 :(得分:2)

找出解决方案:

import operator
from functools import reduce
from django.contrib.admin import ListFilter, FieldListFilter
from django.db.models import Q
from django.contrib.admin.utils import (
    get_fields_from_path, lookup_needs_distinct, prepare_lookup_value,
)
from django.http import QueryDict


class OrListFilter(ListFilter):
    parameter_prefix = None
    fields = None

    def __init__(self, request, params, model, model_admin):
        super(OrListFilter, self).__init__(
            request, params, model, model_admin)
        if self.parameter_prefix is None:
            raise ImproperlyConfigured(
                "The list filter '%s' does not specify "
                "a 'parameter_prefix'." % self.__class__.__name__)

        self.model_admin = model_admin
        self.model = model
        self.request = request
        self.filter_specs = self.get_filters(request, {}, prefix=self.parameter_prefix+'-')

        for p in self.expected_parameters():
            if p in params:
                value = params.pop(p)
                field = p.split('-')[1]
                self.used_parameters[field] = prepare_lookup_value(field, value)

    def has_output(self):
        return True

    # see https://github.com/django/django/blob/1.8.5/django/contrib/admin/views/main.py#L104
    def get_filters(self, request, params, prefix=''):
        filter_specs = []
        for field_path in self.fields:
            field = get_fields_from_path(self.model, field_path)[-1]
            field_list_filter_class = FieldListFilter.create
            spec = field_list_filter_class(field, request, params,
                self.model, self.model_admin, field_path=prefix + field_path)
            # Check if we need to use distinct()
            # use_distinct = (use_distinct or
            #                 lookup_needs_distinct(self.lookup_opts,
            #                                       field_path))
            filter_specs.append(spec)
        return filter_specs

    def expected_parameters(self):
        parameters = []
        for spec in self.filter_specs:
            parameters += spec.expected_parameters()
        return parameters

    def choices(self, cl):
        return []

    def queryset(self, request, queryset):
        origin_GET = request.GET.copy()
        fake_GET = QueryDict(mutable=True)
        fake_GET.update(self.used_parameters)
        request.GET = fake_GET
        all_params = {}
        for spec in self.get_filters(request, self.used_parameters):
            if spec and spec.has_output():
                all_params.update(spec.used_parameters)

        try:
            query_params = [Q((key, value)) for key, value in all_params.items()]
            queryset = queryset.filter(reduce(operator.or_, query_params))
        except TypeError as e:
            pass

        # restore
        request.GET = origin_GET
        return queryset


class OrFilter(OrListFilter):
    title = 'Or filter'
    parameter_prefix = 'or1'
    fields = ("foobar", "foofie")


class FooAdmin(admin.ModelAdmin):
    list_filter = (OrFilter, )

APP_NAME /模板/管理/ APP_NAME / change_list.html:

{% extends "admin/change_list.html" %}
{% load i18n admin_list %}

{% block filters %}
  {% if cl.has_filters %}
    <div id="changelist-filter">
      <h2>{% trans 'Filter' %}</h2>
      {% for spec in cl.filter_specs %}
        {% if spec.filter_specs %}
          {% admin_list_filter cl spec %}
          <ul>
            {% for sub_spec in spec.filter_specs %}
              <li>{% admin_list_filter cl sub_spec %}</li>
            {% endfor %}
          </ul>
        {% else %}
          {% admin_list_filter cl spec %}
        {% endif %}
      {% endfor %}
    </div>
  {% endif %}
{% endblock %}

借用@ dima-kudosh的一些代码。

说明

ChangeList.get_filters()ListFilter创建ModelAdmin.list_filter s(filter_specs),然后使用ListFilter.queryset()get_queryset()

FieldListFilter.queryset()使用used_parameters过滤查询集:queryset.filter(**self.used_parameters)

因此,我们可以从FieldListFilter创建OrListFilter.fields并使用他们的used_parameters构建 OR 查询:

all_params = {}
for spec in self.get_filters(request, self.used_parameters):
    if spec and spec.has_output():
        all_params.update(spec.used_parameters)

try:
    query_params = [Q((key, value)) for key, value in all_params.items()]
    queryset = queryset.filter(reduce(operator.or_, query_params))
except TypeError as e:
    pass

答案 3 :(得分:0)

Django Admin Multiple Choice List Filter是我通过搜索许多类似这样的帖子而编写的,旨在满足这一要求的Django应用。

  

MultipleChoiceListFilter扩展了SimpleListFilter,使您可以筛选多个选项。

用户界面使用可点击的链接来从“或”查询中“包含”和“排除”选择,而不是选中/取消选中复选框。因此,每次单击后,您都必须等待服务器往返,并刷新页面。这可能是性能/ UX问题,尤其是对于大量对象。

“全部”链接和每个选择链接的行为都保留在SimpleListFilter中-也就是说,您可以将过滤器重置为所有选择项,或仅重置其中一个选择项。

当前包含的选项在过滤器中突出显示(在下面的屏幕截图中以蓝色显示)。

该模板是可重写的,因此您可以根据需要更改界面。我个人认为,选择名称和包含/排除链接之间的空格可能会有助于区分两者。也许开关图标比单词“ include” /“ exclude”更直观。

Screenshot from Django Admin Multiple Choice List Filter