zoukankan      html  css  js  c++  java
  • 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格式化,格式化参数也有些许差别

  • 相关阅读:
    集合异常原因与处理方式
    List的子类特点
    数据结构:数据的组织方式
    java对多态的了解
    JAVA电话本系统
    字符串转换数组
    登录用户名密码是否合法
    十三 spark 集群测试与基本命令
    十二 flume与kafka数据传输
    十一 spark- Standalone 集群
  • 原文地址:https://www.cnblogs.com/52-qq/p/11933787.html
Copyright © 2011-2022 走看看