跳转到主要内容

一个将Django模型查询集的聚合函数暴露给DRF API的Python包。

项目描述

django-rest-framework-aggregates

PyPI version Build Status

将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')

测试

为了在本地运行测试

  1. 安装开发需求

    pip3 install -r requirements-dev.txt

  2. 更新您的环境,以便指向测试Django设置文件

    export DJANGO_SETTINGS_MODULE=example.settings.test

  3. 运行测试

    py.test

项目详情


下载文件

下载适合您的平台文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分发

drf-aggregates-0.0.13.tar.gz (5.7 kB 查看散列)

上传时间

构建分发

drf_aggregates-0.0.13-py3-none-any.whl (6.0 kB 查看散列)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面