• Django对postgresql数据库进行分组聚合查询


    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格式化,格式化参数也有些许差别

  • 相关阅读:
    POJ 1741
    POJ 3107
    权限管理
    用户和组
    软件包管理简介
    制作网线
    认识vim编辑器
    linux 进阶命令
    linux 目录&基础命令
    在raw_input()中使用中文提示,在CMD下中文乱码问题解决。。。
  • 原文地址:https://www.cnblogs.com/52-qq/p/11933787.html
Copyright © 2020-2023  润新知