django-filter和聚合函数 [英] django-filter and aggregate functions

查看:276
本文介绍了django-filter和聚合函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是应用特定的问题: django-filter ,以下是针对这些问题的简要说明没有使用过的人

This is an app specific question: django-filter, here is a brief explanation for those who have not used it.

f = ProductFilter(request.GET, queryset=Product.objects.all())

此行为我们完成所有过滤。 ProductFilter 是一个类,我们已经指定了过滤器(类似表单的类)。 f 是一个过滤器对象(基本上是我们要求的项目),其作用类似于列表。

This line does all the filtering for us. ProductFilter is a class, we have specified with filters (forms-alike class). f is a filter object (basically items we have asked for), which acts similar to a list.

现在,我想执行汇总函数(例如 Avg )在此 f 对象上。您是否有想法如何/是否可以实现?

Now, I'd like to perform aggregate functions (like Avg for instance) on this f object. Do you have any ideas how/if this could be accomplished?

推荐答案

您的意思是这样的:

from django.db.models import Avg


class ProductFilter(django_filters.FilterSet):
    ...

    @property
    def avg(self):
        qs = super(ProductFilter, self).qs

        return qs.aggregate(Avg('price'))['id__avg']

因此,您要添加自己的过滤器属性,并在模板中像这样使用它:

So you're adding your own filter property and use it like this in your template:

{{ filter.avg }}

这篇关于django-filter和聚合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆