zoukankan      html  css  js  c++  java
  • Django学习笔记(15)实现模糊查询和精确查询

    Django后端实现模块查询和精确查询

    views.py

     1 from django.db.models import Q
     2 from django.forms import model_to_dict
     3 from django.http import JsonResponse
     4 from django.core.paginator import Paginator
     5 from django.views import View
     6 
     7 class CaseView(View):
     8     def get(self,request):
     9         limit = request.GET.get('limit',20)#分页,获取每页xxx条
    10         page = request.GET.get('page',1)#分页,获取第xxx页
    11         search = request.GET.get('search')#模糊搜索关键字 , 请求: /api/case?search=xxx
    12         filter_field = ['id','title','method']#关键字精确查询,通过哪些字段查询 , 请求: /api/case?id=xxx&title=xxx
    13         filter_dict = {}  #{id:1,title:xxx,method:2}
    14         for field in filter_field:
    15             value = request.GET.get(field)
    16             if value:
    17                 filter_dict[field] = value
    18         if filter_dict:
    19             case_sets = models.Case.objects.filter(**filter_dict)
    20         elif search:#模糊查询
    21             case_sets = models.Case.objects.filter(Q(title__contains=search) |
    22                                    Q(desc__contains=search) |
    23                                    Q(url__contains=search) |
    24                                    Q(params__contains=search))#模糊查询
    25         else:
    26             case_sets = models.Case.objects.filter(is_delete=False)#查询所有
    27 
    28         paginator = Paginator(case_sets,limit) #分页,获取分页对象
    29         page_data = paginator.page(page)  #分页,获取分页数据,返回的是model对象
    30 
    31         data = []
    32         for c in page_data:#分页字典拼接成list
    33             d = model_to_dict(c)
    34             data.append(d)
    35         response = {'code': 0, 'msg': '添加成功', 'data': data,'count':paginator.count}
    36         return JsonResponse(response, json_dumps_params={'ensure_ascii': False})  # 汉字不转义
  • 相关阅读:
    [CTSC2008]网络管理
    [HNOI/AHOI2018]转盘
    [HAOI2015]树上染色
    [CTSC2017]吉夫特
    [CTSC2011]幸福路径
    Comet OJ
    2019各省省选试题选做
    HNOI2019 简要题解
    HNOI2019游记
    JOISC2019 简要题解
  • 原文地址:https://www.cnblogs.com/bugoobird/p/13371187.html
Copyright © 2011-2022 走看看