Example of Fuzzy Query by models in python Django

  • 2021-07-22 10:42:11
  • OfStack

Multi-field fuzzy query, the underline in brackets is double underline, before the double underline is the field name, after the double underline can be icontains or contains, the difference is whether it is case sensitive, the vertical line is or


# Search function 
@csrf_exempt# Use @csrf_exempt Decorator, exempt csrf Validation 
def search_testCaseApi(request):
  if request.method == 'POST':
    name = request.POST.get('task_name')
    updateUser=request.POST.get('task_updateUser')
    if name=="" and updateUser=="":
      obj_all = tnw_test_case_api.objects.filter(del_flag=0)
    elif name!="" and updateUser=="":
      obj_all = tnw_test_case_api.objects.filter(del_flag=0,case_name__contains=name)
    elif name=="" and updateUser!="":
      obj_all = tnw_test_case_api.objects.filter(del_flag=0,update_user__contains=updateUser)
    else:
      obj_all = tnw_test_case_api.objects.filter(del_flag=0,case_name__contains=name,update_user__contains=updateUser)
    ApiCasesList = []
    for li in obj_all:
      need_interfacename = allFunction().get_interfaceName(li.id)
      api_list, api_sum = allFunction().testIDConnect_needid(li.id)
      if li.case_module is not None:
        ApiCasesList.append({
          "testCaseApi_id": li.id,
          "testCaseApi_name": li.case_name,
          "testCaseApi_sum": api_sum,
          "testCaseApi_version": li.case_version,
          "testCaseApi_module": li.case_module,
          "testCaseApi_need_interfacename": need_interfacename,
          "testCaseApi_createTime": str(li.create_time),
          "testCaseApi_updateTime": str(li.update_time),
          "testCaseApi_updateUser": li.update_user,
        })
      else:
        ApiCasesList.append({
          "testCaseApi_id": li.id,
          "testCaseApi_name": li.case_name,
          "testCaseApi_sum": 1,
          "testCaseApi_version": li.case_version,
          "testCaseApi_module": li.case_module,
          "testCaseApi_need_interfacename": need_interfacename,
          "testCaseApi_createTime": str(li.create_time),
          "testCaseApi_updateTime": str(li.update_time),
          "testCaseApi_updateUser": li.update_user,
        })
    #  Will int Type usage dumps() Method conversion str Type 
    ApiCasesList_len = json.dumps(len(ApiCasesList))
    #  Structure 1 A dictionary 
    json_data_list = {'rows': ApiCasesList, 'total': ApiCasesList_len}
    # dumps() Convert a dictionary to json Form ,
    easyList = json.dumps(json_data_list)
    #  Will json Go back, json The key in the key-value pair of needs to be related to the foreground table field= " X "In X Name retention 1 To) 
    return HttpResponse(easyList)

Related articles: