正在部署和删除过滤器 django



我有date_fromdate_tostudentAstudentB过滤器。

我希望能够使用其中一个、其中一些、全部或一次不使用它们来过滤数据。它们都不意味着显示整个数据 - 没有应用过滤器。

比如说,我选择按日期范围过滤并提交。我看到了所选时期的数据。现在,如果我清除表单(日期范围过滤条件),整个数据应该会再次弹出 - 因为没有使用过滤器。

为了使它工作,我在views.py中定义了条件:

if (    form.is_valid() 
    and len(request.GET['date_from']) > 0 
    and len(request.GET['date_to']) > 0
    ): 
    date_from = form.cleaned_data['date_from']
    date_to = form.cleaned_data['date_to']
    attendance = Students.objects.filter(
                        date__range=(date_from, date_to))

如果我没有这种情况,那么,当我清除上述步骤中的过滤器时,不会弹出任何数据。

当我有一个或两个过滤器时,这不是问题,但随着更多过滤器的出现,代码开始快速增长 - 我必须做很多elif语句,例如。

elif (    form.is_valid() 
    and len(request.GET['date_from']) > 0 
    and len(request.GET['date_to']) > 0
    and len(request.GET['studentA']) > 0
    ): 
    # apply this filter
elif (    form.is_valid() 
    and len(request.GET['studentA']) > 0
    ):
    # apply this one

等等。

我的问题是,是否有任何替代的、不那么冗长的方法来来回应用和删除过滤器(我确定有)?

我会使用django-filter(https://github.com/alex/django-filter)来做这种事情。它为您完成所有过滤。它只是为您提供了一个可以显示的Form

编辑:

对于范围日期筛选器(开始和结束日期),您只需添加 2 个筛选器,一个用于lte查找,另一个具有gte查找。例如:

date_start = django_filters.DateFilter(name='{date field to filter}' lookup_type='gte')
date_end = django_filters.DateFilter(name='{date field to filter}' lookup_type='lte')

最新更新