搜索功能应该在过滤完后也能使用,所以在调用过滤方法后调用 table_search
查询条件有多个,所以这时使用复杂查询 Q。 返回 search_key 让搜索框保留搜索内容
from django.db.models import Q
def table_search(request, models_list, admin_class):
search_key = request.GET.get('_q','')
q_obj = Q()
q_obj.connector = 'OR' # 指定过滤方式是 ’或‘
for search_field in admin_class.search_fields: # 把搜索内容_q 与每个search字段都组成一个元组
q_obj.children.append(('%s__contains'%search_field, search_key))
return models_list.filter(q_obj), search_key
前端代码
- placeholder
输入框提示内容
<div class="row">
<div class="col-lg-3" style="margin-top: 10px">
<input type="search" class="form-control" placeholder="search by {% for search_field in admin_class.search_fields %}{{ search_field }} {% endfor %}"
value="{{ search_key }}" name="_q">
</div>
<div class="col-lg-1">
<button type="submit" class="btn btn-success" style="margin-top: 10px">search</button>
</div>
</div>
网友评论