一个将Django模型查询集的聚合函数暴露给DRF API的Python包。
项目描述
django-rest-framework-aggregates
将Django模型查询集的聚合功能暴露给DRF API。
需求
- Python 3.6+
- Django 1.11+
- Django Rest Framework 3.5.3+
概述
此渲染器覆盖了针对api v2 .agg端点的调用默认行为。
支持对列表端点的 GET
调用
endpoint.agg/?aggregate[Count]=(field to count)
endpoint.agg/?aggregate[Sum]=(field to sum)
endpoint.agg/?aggregate[custom_function]=arguments
endpoint.agg/?group_by[field to group by]&aggregate[Count]=id
endpoint.agg/?group_by[field to group by]&aggregate[Count]=id&aggregate[Sum]=(field to sum)
支持日期部分提取以进行聚合
endpoint.agg/?group_by[created__year]&aggregate[Count]=id
支持选择表示提取
endpoint.agg/?group_by[choiceField]&aggregate[Count]=id
支持跨多个字段聚合,可以是
endpoint.agg/?aggregate[Sum]=id&aggregate[Sum]=number
endpoint.agg/?aggregate[Sum]=id,number
自定义聚合
支持的默认聚合函数定义在 django.db.models.aggregates
中。
自定义聚合函数已定义在 drf_aggregates.aggregates
中。
如果定义了,用户自定义的聚合将作为kwargs传递给自定义查询集管理器 calculate_aggregates
。
在查询集上设置的自定义聚合函数应返回一个字典,其中包含字段名到聚合函数的映射,然后与其他聚合一起处理。
示例
示例设置可以在 example/ 文件夹中找到。
要启用渲染器,更新您的Django设置文件
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'drf_aggregates.renderers.AggregateRenderer',
...
),
...
}
在 Cars ViewSet 中,我们将结果输出到json
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
data = request.accepted_renderer.render({'queryset': queryset, 'request': request})
return Response(data, content_type=f'application/json')
测试
为了在本地运行测试
-
安装开发需求
pip3 install -r requirements-dev.txt
-
更新您的环境,以便指向测试Django设置文件
export DJANGO_SETTINGS_MODULE=example.settings.test
-
运行测试
py.test