CRM项目动态搜索功能

搜索功能应该在过滤完后也能使用,所以在调用过滤方法后调用 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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容