hr504883750 2018-11-13 01:53 采纳率: 0%
浏览 1335

flask sqlalchemy 查询优化 哪位大神帮忙

 @admin_blueprint.route('/videos_count')
def user_count():
    # 视频总数
    videos_total = Videos.query.filter(or_(Videos.status == 1, Videos.status== 6)).count()


    # 月视频更新总数
    now = datetime.now()
    month_first = datetime(now.year, now.month, 1)
    videos_month = Videos.query. \
        filter_by(status=1). \
        filter(Videos.created_at >= month_first). \
        count()

    # 日视频更新数
    day_first = datetime(now.year, now.month, now.day)
    videos_day = Videos.query. \
        filter_by(status=1). \
        filter(Videos.created_at >= day_first). \
        count()

    # 小时视频更新数
    video_key = 'videos_count_%d_%d_%d' % (now.year, now.month, now.day)
    video_prop = ['02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00',
                  '00:00']
    hour_list = [x.split(":")[0] for x in video_prop]
    hour_list = [datetime(now.year, now.month, now.day, int(y)) for y in hour_list]
    hour_list.pop()
    # 生成分段时间轴
    month_day = calendar.monthrange(now.year, now.month)[1]
    if now.day == month_day:
        hour_list.append(datetime(now.year, now.month + 1, 1, 00))
    else:
        hour_list.append(datetime(now.year, now.month, now.day + 1, 00))
    index_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    videos_hour_count = []
    for index, hour_first in list(zip(index_list, hour_list)):
        if index == 0:
            date_time = (datetime(now.year, now.month, now.day, 00))
            videos_hour_num = Videos.query. \
                filter(Videos.status == 1, date_time < Videos.created_at,
                       Videos.created_at <= hour_first).\
                count()
            videos_hour_count.append(videos_hour_num)
        else:
            videos_hour_num = Videos.query. \
                filter(Videos.status == 1, hour_list[index - 1] < Videos.created_at,
                       Videos.created_at <= hour_first).\
                count()
            videos_hour_count.append(videos_hour_num)
    return render_template('admin/videos_count.html',
                           videos_total=videos_total,
                           videos_month=videos_month,
                           videos_day=videos_day,
                           videos_hour_count=videos_hour_count,
                           videos_hour_list=video_prop
                           )

这是一段根据时间段,分段的查询,数据比较多,查询一次要一秒,怎么整合成一次查询,或者说把for循环的查询优化,急,打开网页一次要18秒

  • 写回答

1条回答 默认 最新

  • 地址ch3nye.top 2019-08-31 13:20
    关注

    我来提个建议:如果内存足够的话,一次查出所有数据,得到的是list,进行筛选
    numpy.sum(list(map(lambda x:x.time 符合 xxx, list)))

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!