Django中如何统计各状态任务总数量并用于Chartjs展示?
实现方案
1. 后端统计状态数量(Django视图层)
直接用Django ORM的聚合分组查询,效率远高于多次单独查询,同时自动处理无任务状态的默认值补0:
from django.db.models import Count from django.shortcuts import render from django.http import JsonResponse from .models import Todo def todo_status_stat(request): # 按任务状态分组统计数量 status_qs = Todo.objects.values("status").annotate(total=Count("id")) # 转为字典方便取值 count_map = {item["status"]: item["total"] for item in status_qs} # 按要求的顺序生成数组,不存在的状态默认值为0 status_count = [ count_map.get("to_do", 0), count_map.get("in_progress", 0), count_map.get("done", 0) ] # 两种输出方式二选一: # 方式1:模板渲染直接传参 # return render(request, "你的模板路径.html", {"status_count": status_count}) # 方式2:前后端分离返回JSON接口 return JsonResponse({"status_count": status_count})
如果需要按团队、项目、时间范围筛选统计,只需要在Todo.objects后追加filter条件即可,比如按项目过滤:Todo.objects.filter(project_id=目标项目ID).values("status")...
2. 前端对接ChartJS渲染
首先在页面中准备图表画布,然后对接后端返回的数组渲染即可:
<!-- 图表画布 --> <canvas id="todoChart" width="400" height="250"></canvas> <script> // 模板渲染场景直接读取后端传的参数 // const countData = {{ status_count|safe }}; // 接口请求场景示例 fetch("/你的接口路径/") .then(response => response.json()) .then(res => { const countData = res.status_count; const ctx = document.getElementById("todoChart").getContext("2d"); // 初始化图表,可根据需求修改type为bar、doughnut等类型 new Chart(ctx, { type: "pie", data: { labels: ["待办", "进行中", "已完成"], datasets: [{ label: "任务数量", data: countData, backgroundColor: [ "rgba(255, 99, 132, 0.6)", "rgba(255, 206, 86, 0.6)", "rgba(75, 192, 192, 0.6)" ], borderWidth: 1 }] }, options: { responsive: true } }); }) </script>
内容的提问来源于stack exchange,提问作者Niki Grey
相关产品推荐
相关产品推荐

