# 搜索|在已经过滤的条件之下做搜索; # 在查询语句中,用"包含"来做模糊搜索: # 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.py def get_filter_result(request,querysets): filter_conditions = {} for key,val in request.GET.items(): # 分页,排序,搜索的参数对过滤没有影响; if key in (‘page‘,‘_o‘,‘_q‘):continue ... # 搜索完之后再排序; # 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) # 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 }}">