查詢思路
首先在Django的models中要有DateTimeField數據類型的字段,假定我的字段是CreateTime。
但是DateTimeField在數據庫中顯示的是:2019-03-05 15:57:28.430312
思路:
- 按年月篩選數據
- 格式化日期爲天
- 將數據按天分組
- 統計每組數據的條數
- 輸出查詢結果
操作
爲了實現按天分組,首先要按年月篩選數據,這一步可以使用ORM中的
filter(CreateTime__year=2019, CreateTime__month=03)
下一步就是按天分組,統計每天的數據條數。
這一步必須要格式化日期,將日期格式化成天數,再分組,統計每天的數據條數,輸出。
格式化日期可以使用:
extra(select={"CreateTime": "DATE_FORMAT(CreateTime, '%%e')"})
分組:
values('CreateTime')
統計數據:
annotate(count_len=Count('CreateTime')).values('CreateTime', 'count_len')
輸出結果:
<QuerySet [{'CreateTime': '5', 'count_len': 34}]>
全部代碼
- models中要有DateTimeField類型的字段 CreateTime
count_data = storage_log.objects.filter(CreateTime__year=this_year, CreateTime__month=this_month)\
.extra(select={"CreateTime": "DATE_FORMAT(CreateTime,'%%e')"}).values('CreateTime')\
.annotate(send_num=Count('CreateTime')).values('CreateTime', 'count_len')