利用Trunc統(tǒng)計日月周的數(shù)據(jù)
django 官網(wǎng)地址https://docs.djangoproject.com/en/2.2/ref/models/database-functions/
在統(tǒng)計數(shù)據(jù)中,我們會經(jīng)常需要統(tǒng)計每天時間或者每月時間的數(shù)據(jù),以前都是通過extra自己寫select完成需求,現(xiàn)在有Trunc類,可以簡單的實現(xiàn)統(tǒng)計的功能
比如下面統(tǒng)計每年(統(tǒng)計每天就是換成TruncDate):
>>> from datetime import datetime
>>> from django.db.models import Count
>>> from django.db.models.functions import TruncMonth, TruncYear
>>> from django.utils import timezone
>>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
>>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
>>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
>>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
>>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
>>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
>>> experiments_per_year = Experiment.objects.annotate(
... year=TruncYear('start_date')).values('year').annotate(
... experiments=Count('id'))
>>> for exp in experiments_per_year:
... print(exp['year'], exp['experiments'])
...
2014-01-01 1
2015-01-01 2
在django.db.models.function中還有很多其他的方法
TruncMonth : 月份
TruncYear : 年份
TruncWeek :周(在django2.1中才有)
TruncQuarter : 季度
TruncHour
TruncMinute
TruncSecond
TruncDay