django 时间筛选

2020-01-09  本文已影响0人  叶叶阿姨

两种方法:
1.orm查询的方法

def api_back_time_news(request):
   # 时间筛选
   if request.POST.get('time'):
      #从前端获取到时间拆分出开始时间和结束时间
       start_time = request.POST.get('time').split(',')[0]
       end_time = request.POST.get('time').split(',')[1]
       #时间查询
       post_list = Alerts.objects.filter(alerts_releasetime__gte=start_time,
                                         alerts_releasetime__lte=end_time).all()
       #查询后总数
       count = post_list.count()
       #拼数据返给前端
       data = []
       for a in post_list:
           data.append(dict(a.api_to_dict()))
       return JsonResponse({'msg': '获取成功', 'code': 200, 'data': data, 'count': count})

2.sql查询方法

def api_back_time_news(request):
    # 时间筛选
    if request.POST.get('time'):
        print(request.POST.get('time'))
        cursor = connection.cursor()
        start_time = request.POST.get('time').split(',')[0]
        end_time = request.POST.get('time').split(',')[1]
        page = int(request.POST.get('page', 1))
        limit = int(request.POST.get('limit', 10))
        cursor.execute(f'select * from quick_poll_alerts where alerts_releasetime >= "{start_time}" and alerts_releasetime <= "{end_time}"' \
                       f'order by alerts_releasetime desc limit {(page - 1) * limit},{limit}')
        data = [format_alerts_list(i) for i in cursor.fetchall()]
        cursor.execute(f'select count(*) from quick_poll_alerts where alerts_releasetime >= "{start_time}" and alerts_releasetime <= "{end_time}"' \
            f'order by alerts_releasetime desc limit {(page - 1) * limit},{limit}')
        count = cursor.fetchall()
        cursor.close()
        return JsonResponse({'msg': '添加成功', 'code': 200, 'data': data, 'count': count})

这里的format_alerts_list是格式化sql输出

def format_alerts_list(data, key=None, type=None, label=None):
    ret = {}
    # id
    ret['id'] = data[0]
    # img
    ret['img'] = data[3]
    # title
    ret['title'] = data[12]
    # abstract
    ret['abstract'] = data[2]
    # niche
    ret['niche'] = Niche.objects.filter(id=data[6]).first().niche_name
    # article
    ret['article'] = Article.objects.filter(id=data[4]).first().alerts_section_name
    # time
    ret['time'] = data[11].strftime("%Y-%m-%d")
    # source
    ret['source'] = Source.objects.filter(id=data[10]).first().source_name
    # regional
    ret['regional'] = Regional.objects.filter(id=data[7]).first().regional_name
    # content
    if type == 'detail':
        ret['content'] = data[1]
    if label:
        ret['label'] = data[13]
    return ret
上一篇下一篇

猜你喜欢

热点阅读