hr504883750
hr504883750
采纳率0%
2018-11-13 01:53 阅读 1.2k

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条回答 默认 最新

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

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

    点赞 评论 复制链接分享

相关推荐