You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:18:02