Django-筛选过滤器对象

时间:2018-02-25 12:46:05

标签: django django-queryset django-filter

我想使用FilterSets在页面上进行复杂的过滤。这是我的Filterset,很好地向我展示了所选时间和所选参数的元组。

# filters.py

class workFilter(filters.FilterSet):
    start__gt = filters.DateTimeFilter(name='time_start', lookup_expr='gte')
    start__lt = filters.DateTimeFilter(name='time_end', lookup_expr='lte')

    class Meta:
        model = Work
        fields = ('machine', 'program')

但我想添加解释查询数据的图表。为此我需要信息,比如整体时间。我这样询问他们:

#views.py

def search(request):
    work_list = Work.objects.all()
    work_filter = workFilter(request.GET, queryset=work_list)
    filter_backends = (filters.DjangoFilterBackend,)

    #some queries to add to context, such as
    sum_work = Work.objects.aggregate(Sum('time'))['time__sum']

    return render_to_response(
        TEMPLATE_DIRS + 'index.html',
        {
            'filter': praca_filter,
            'sum_work': sum_work,
        }
    )

但遗憾的是,这些查询是根据整个数据库而不是我过滤的对象集。

如何对过滤集work_filter进行查询?

1 个答案:

答案 0 :(得分:0)

sum_work定义为FilterSet的属性。

class WorkFilter(filters.FilterSet):
    start__gt = filters.DateTimeFilter(name='time_start', lookup_expr='gte')
    start__lt = filters.DateTimeFilter(name='time_end', lookup_expr='lte')

    class Meta:
        model = Work
        fields = ('machine', 'program')

    @property
    def work_sum(self):
        qs = super(WorkFilter, self).qs

        return qs.aggregate(Sum('time'))['time__sum']

然后,当您将过滤器传递到视图时,您只需在模板中使用{{ filter.work_sum }}