自动化测试平台开发(十):接口测试 - 问题记录 - DRF实现分组查询
前面几篇做了前后端核心功能实现的示例,然后就记录最终demo结果。但是实现起来,期间踩过好些坑。本篇开始总结一下这期间遇到的问题即解决方案。
Django restframework ViewSet 封装实现分组查询
from django.db.models import Count from rest_framework.viewsets import GenericViewSet from rest_framework import filters from django_filters.rest_framework import DjangoFilterBackend class GroupCountModelMixin(GenericViewSet): """Count a queryset by group.""" filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] default_group_by_field = 'id' # string, field default_time_unit = '' # string, type(group_by_field)=DateTimeField --> year | month | day time_unit_str = { 'year': '%%Y', 'month': '%%Y-%%m', 'week': '%%x-%%v', 'day': '%%Y-%%m-%%d', } def list(self, request, *args, **kwargs): """ 分组查询 :param request: group_by_field: 分组字段 time_unit: 若按时间分组,可设置时间单位 year | month | day :param args: :param kwargs: :return: """ group_by_field = self.default_group_by_field time_unit = self.default_time_unit if 'group_by_field' in request.query_params: request.query_params._mutable = True group_by_field = request.query_params.get('group_by_field') request.query_params.__delitem__('group_by_field') request.query_params._mutable = False if 'time_unit' in request.query_params: request.query_params._mutable = True time_unit = request.query_params.get('time_unit') request.query_params.__delitem__('time_unit') request.query_params._mutable = False extra_select = { group_by_field: "DATE_FORMAT({}, '{}')".format(group_by_field, self.time_unit_str[time_unit]) } if time_unit else {} queryset = self.filter_queryset(self.get_queryset().extra(select=extra_select).values(group_by_field)).\ order_by(group_by_field).annotate(count=Count("id")).values(group_by_field, "count") return Response(data=list(queryset.all()), status=200)