CRM手記-8 | Django
阿新 • • 發佈:2018-01-21
pen req 後端 實例化 排序 數據 inpu obj lds
# 搜索|在已經過濾的條件之下做搜索; # 在查詢語句中,用"包含"來做模糊搜索: # model_class.objects.filter(contact__contains=‘33‘) # 涉及到Q的操作;這裏通過Q這個類來實現; # table_obj_list.html <form> <input type="search" name="_q"> <input type="submit" value="搜索"> </form> # views.pydef get_filter_result(request,querysets): filter_conditions = {} for key,val in request.GET.items(): # 分頁,排序,搜索的參數對過濾沒有影響; if key in (‘page‘,‘_o‘,‘_q‘):continue ... # 搜索完之後再排序; # views.py @login_requireddef table_obj_list(request,app_name,model_name): ... # 4.返回搜索結果 # admin_class獲知所有可以搜索的條件; # request參數獲知當前搜索條件,改變搜索結果querysets; querysets = get_searched_result(request,querysets,admin_class) # 2.排序後端數據查詢 ...# 3.分頁 ... return render(request,‘kingadmin/table_obj_list.html‘, { ‘querysets‘:querysets, ‘admin_class‘:admin_class, ‘current_page‘:current_page, ‘current_order_field‘:current_order_field }) from django.db.models import Q # 獲取搜索結果 def get_searched_result(request,querysets,admin_class): search_key = request.GET.get(‘_q‘) if search_key: # 1.實例化Q q = Q() # 2.確定邏輯符號 q.connector = ‘OR‘ for search_field in admin_class.search_fields: # 3.添加條件 # append()傳入一個元組,字符串格式化跟著元組表示傳入多個參數,沒有元組表示生成多個字符串; q.children.append(("%s__contains"%search_field,search_key)) # 4.q查詢 return querysets.filter(q) return querysets # 在過濾條件下搜索 # 添加隱藏的搜索框將過濾條件在搜索的表單中一並提交; # table_obj_list.html <form> <input type="search" name="_q"> <!-- 將當前過濾條件通過表單提交 --> {% for k,v in admin_class.filter_condtions.items %} <input type="hidden" name={{ k }} value={{ v }}> {% endfor %} <input type="submit" value="搜索"> </form> # 添加value顯示正在搜索的條件 # 在搜索查詢之後,獲取url中的參數值,傳遞到前端隱藏標簽的value中; # views.py @login_required def table_obj_list(request,app_name,model_name): ... # 4.返回搜索結果 # admin_class獲知所有可以搜索的條件; # request參數獲知當前搜索條件,改變搜索結果querysets; querysets = get_searched_result(request,querysets,admin_class) # 4.1 顯示正在搜索的條件 admin_class.search_key = request.GET.get(‘_q‘,‘‘) ... # table_obj_list.html <input type="search" name="_q" value="{{ admin_class.search_key }}">
CRM手記-8 | Django