django-filter and aggregate functions

北战南征 提交于 2019-12-10 18:24:20

问题


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())

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.

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?


回答1:


You mean something like this:

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 }}


来源:https://stackoverflow.com/questions/18964002/django-filter-and-aggregate-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!