在Django中如何从日期字段获取近6个月员工入职统计数据?
解决方案
可以通过Django ORM结合日期处理工具实现需求,步骤如下:
1. 导入必要模块
需要用到Django的聚合函数、日期截断工具,以及Python的日期处理库:
from django.db.models import Count from django.db.models.functions import TruncMonth from datetime import datetime from dateutil.relativedelta import relativedelta
2. 计算日期范围
确定近6个月的起始日期(当前日期往前推6个月):
today = datetime.today() six_months_ago = today - relativedelta(months=6)
3. 查询并统计数据
使用TruncMonth将joining_Date截断到月份级别,再按月份分组统计入职人数:
employee_stats = Employee.objects.filter( joining_Date__gte=six_months_ago ).annotate( month=TruncMonth('joining_Date') ).values('month').annotate( count=Count('id') ).order_by('-month')
4. 格式化输出目标格式
将查询结果转换为指定的月份名称对应数量格式,同时补全无数据的月份(确保6个月全部显示):
# 生成近6个月的月份名称列表(从当月往前推) month_names = [] current_month = today for _ in range(6): month_name = current_month.strftime('%B') month_names.append(month_name) current_month -= relativedelta(months=1) # 将查询结果转为月份名称对应数量的字典 stats_dict = {} for item in employee_stats: month_name = item['month'].strftime('%B') stats_dict[month_name] = item['count'] # 补全缺失月份的数量为0 for month in month_names: stats_dict.setdefault(month, 0) # 按要求格式输出 for month in month_names: print(f"{month} : {stats_dict[month]},")
补充说明
- 若未安装
python-dateutil,执行pip install python-dateutil完成安装 TruncMonth会将日期转为当月第一天(如2022-07-22转为2022-07-01),用于统一月份分组标准- 循环生成6个月的月份列表,确保即使某月份无入职员工,也会显示对应数量0
内容的提问来源于stack exchange,提问作者Saravanan Ragavan
相关产品推荐
相关产品推荐

