如何在graphene-django中创建自定义对象返回按条件分组统计计数
Django Task 分组统计计数实现方案
统计规则梳理
根据你提供的样本数据和期望返回结果,对应统计逻辑如下(可根据实际业务调整判断条件):
- behind schedule(逾期):任务截止日期早于开始日期,共2条匹配
- in progress(进行中):未逾期且任务状态为
in progress/assigned,共2条匹配 - completed(已完成):未逾期且任务状态为
completed,共1条匹配
核心实现代码
使用Django ORM的条件注解+分组统计功能实现:
from django.db.models import Count, Case, When, F, Value, CharField # 条件标记类别+分组统计 task_count_result = Task.objects.annotate( count_type=Case( # 优先判断逾期 When(due_date__lt=F('start_date'), then=Value('behind schedule')), # 再判断进行中 When(task_status__in=['in progress', 'assigned'], then=Value('in progress')), # 已完成 When(task_status='completed', then=Value('completed')), default=Value('other'), output_field=CharField() ) ).values('count_type').annotate(count=Count('id')).order_by()
执行后返回的结果格式为:
<QuerySet [ {'count_type': 'behind schedule', 'count': 2}, {'count_type': 'in progress', 'count': 2}, {'count_type': 'completed', 'count': 1} ]>
扩展用法
如果仅需要按task_status原生值直接分组统计,无需自定义类别,使用更简洁的语句即可:
raw_status_count = Task.objects.values('task_status').annotate(count=Count('id')).order_by()
返回格式封装
如果需要匹配你示例中的嵌套结构,直接对查询结果做二次封装即可:
response_data = { "getTaskCounts": { "taskCount": list(task_count_result) } }
内容的提问来源于stack exchange,提问作者OpenDataAlex
相关产品推荐
相关产品推荐

