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

如何在Django中统计含零值的各服务呼叫量?

Django统计指定时间段各服务呼叫数(包含无数据服务)

你的问题出在查询起点选错了:从Survey模型过滤时,只有存在符合条件Survey记录的服务才会被返回,没有对应Survey的S3自然不会出现在结果里。要包含所有指定服务,需从Service模型出发,结合Coalesce将空统计值转为0,实现如下:

代码实现

首先导入所需工具:

from django.db.models import Count, Q
from django.db.models.functions import Coalesce
import datetime

然后编写查询逻辑:

start = datetime.datetime(2024, 6, 17, 0, 0)
end = datetime.datetime(2024, 6, 17, 23, 59, 59)
services = <QuerySet [<Service: S1>, <Service: S2>, <Service: S3>]>  # 你的目标服务集合

# 从Service出发统计关联的符合条件的Survey数量
result = services.annotate(
    nb=Coalesce(
        # 仅统计指定时间段内的Survey记录
        Count('survey', filter=Q(survey__when_start__range=(start, end))),
        0  # 当无匹配记录时返回0
    )
).values('name', 'nb')

关键说明

  1. 查询起点切换:从Service集合出发,利用反向关联survey(对应模型中related_name='survey'),相当于做左连接,会保留所有指定的服务,即使没有对应的Survey记录。
  2. 带过滤的Count:Count的filter参数只统计符合时间段条件的Survey,避免统计无关数据。
  3. Coalesce的作用:当某个服务没有符合条件的Survey时,Count会返回None,Coalesce将其替换为0,满足你要显示0的需求。

执行后就能得到你期望的结果:

<QuerySet [{'name': 'S1', 'nb': 50}, {'name': 'S2', 'nb': 119}, {'name': 'S3', 'nb': 0}]>

内容的提问来源于stack exchange,提问作者Aurélien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:32:43