纵有疾风起
人生不言弃

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

文章转载于:https://www.cnblogs.com/52-qq/p/11933787.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » Django对postgresql数据库进行分组聚合查询
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录