action(methods=['GET'], detail=False, url_path='count') def count(self, request): """统计最近30天的抓拍记录""" starttime = request.query_params.get('starttime') endtime = request.query_params.get('endtime') days = datetime.timedelta(days=1) start_date = datetime.datetime.strptime(starttime, '%Y%m%d%H%M%S').date() end_date = datetime.datetime.strptime(endtime, '%Y%m%d%H%M%S').date() count_list = { 'dates': { 'start_date': start_date, 'end_date': end_date }, 'result': [] } if end_date - start_date == days: result_list = models.DevicePhotoModel.objects.filter(take_photo_time__range=(start_date, end_date)) .extra(select={"take_photo_time": "to_char(take_photo_time, 'HH')"}).values('take_photo_time') .annotate(count=Count('take_photo_time')).values('take_photo_time', 'count') # 统计当天的数据 else: result_list = models.DevicePhotoModel.objects.filter(take_photo_time__range=(start_date, end_date)) .extra(select={"take_photo_time": "to_char(take_photo_time, 'yyyy-mm-dd')"}).values('take_photo_time') .annotate(count=Count('take_photo_time')).values('take_photo_time', 'count') for result in result_list: count_list['result'].append({ 'date': result['take_photo_time'], 'count': result['count'] }) return Response(count
mysql和postgres数据库格式化方法不同。网上找了很多格式化案例,但是都会报错。mysql中用DATE_FORMAT格式化,postgresql中用TO_CHAR格式化,格式化参数也有些许差别