filter检查并清除过滤器

filter检查并清除过滤器

本文介绍了使用django-filter检查并清除过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 django-filter 来过滤 ListView ,并且如果应用了任何过滤器,则希望显示清除所有过滤器"链接.

I am using django-filter to filter a ListView and would like to display a "Clear all filters" link if any filters are applied.

由于过滤系统的一般性质,我尚未找到实现此目的的直接方法.

Due to the generic nature of the filtering system I haven't yet found a straightforward way to achieve this.

到目前为止,我唯一想到的是如果请求中存在清除"标志,则在视图的 get_queryset 方法中返回常规queryset,但这实际上并没有清除过滤器-它只返回所有数据.

The only thing I came up with so far is to return the regular queryset in the get_queryset method of the view if a "clear" flag is present in the request, however this doesn't actually clear the filters - it just returns all the data.

有人对此有解决方案/想法吗?

Does anyone have a solution/idea for this?

更新:解决方案

在Jerin发表评论后,我决定分两个部分解决此问题:

After Jerin's comment I decided to solve this problem in 2 separate parts:

具有过滤器:

我检查在过滤器类中定义的任何字段是否在请求中.我的解决方案看起来有些不同,因为我使用的是基于类的视图,因此我将其抽象化为mixin,但是如果您使用的是简单视图,则像这里,您可以这样做:

I check if any of the fields I defined in my filter class are in the request. My solution looks a bit different as I'm using class based views so I abstracted it away in a mixin but if you're using simple views like here, you could just do:

def product_list(request):
    f = ProductFilter(request.GET, queryset=Product.objects.all())
    has_filter = any(field in request.GET for field in
set(f.get_fields()))

    return render(request, 'my_app/template.html', {
        'filter': f,
        'has_filter': has_filter
    })

清除所有过滤器:

一个简单的重定向到您的列表视图:

A simple redirect to your list view:

{% if has_filter %}
  <a href="{%  url 'products' %}">{% trans 'Clear all filters' %}</a>
{% endif %}

推荐答案

以下是答案的混合版本(我的和的组合克里斯(Chris))

您可以放置​​一个清除所有过滤器按钮,该按钮将重定向到默认的ListView(/host/end/point/).但是,URL中可能会出现一些 non-filter参数(例如 pagination 或其他内容).因此,更好的选择是,检查URL中是否有任何过滤器字段,如果是,则显示过滤器清除链接

选择的解决方案是

Here is the mixup version of the answer (combination of mine and Chris)

You could place a Clear all filters button and that will redirect to your default ListView (/host/end/point/).But some non-filter parameters (such as pagination or something else) may occur in URL. So the better option is, check for any filter fields in URL and if so, display the filter clearing link

The opted solution is,

def product_list(request):
    f = ProductFilter(request.GET, queryset=Product.objects.all())
    has_filter = any(field in request.GET for field in set(f.get_fields()))

    return render(request, 'my_app/template.html', {
        'filter': f,
        'has_filter': has_filter
    })


在模板中,


and in template,

{% if has_filter %}
  <a href="{%  url 'products' %}">{% trans 'Clear all filters' %}</a>
{% endif %}

这篇关于使用django-filter检查并清除过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 08:35