Django多条件动态查询:基于字典传参的高效实现方案

咖啡半糖
咖啡半糖
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍在Django项目中处理多条件动态查询的高效方法。通过收集前端提交的多个可选参数,构建Python字典,并利用filter(**dict)语法将字典解包为查询条件,可避免繁琐的if-else判断。文章结合视图函数、HTML表单及Ajax异步提交代码,展示了从数据获取、条件组装到前端渲染的完整流程,适用于CMS等需要灵活搜索功能的场景。

Django多条件动态查询:基于字典传参的高效实现方案

本文主要探讨在Django框架中如何优雅地处理多条件查询场景。

在许多内容管理系统(CMS)或后台管理项目中,用户往往需要根据多个维度进行数据筛选。后端如何高效接收并处理这些动态变化的查询条件,是一个常见的技术痛点。

当查询条件仅包含单一字段时,逻辑相对简单。

若需同时满足两个条件的组合查询,代码结构开始变得复杂。

而在实际业务中,通常需要支持多个条件的任意组合查询。

………………….

如果采用传统的逐个判断方式,代码会变得冗长且难以维护,令人头疼。虽然存在传参、传字典、使用Q对象或F对象等多种解决方案,但如何以简洁的方式实现这一需求仍需深入思考。

个人推荐的做法是将所有查询条件封装为一个字典,通过Django的filter方法配合字典解包来实现高效查询。具体实现细节见下文代码。

视图函数实现逻辑

以下是视图函数的具体实现逻辑。


def order_list(request):
  
  if request.method == 'GET':
    return render(request, 'admin/order_list.html')

  if request.method == 'POST':
    # 获取案件号
    case_order = request.POST.get('case_order')
    # 获取客户姓名
    case_name = request.POST.get('case_name')
    # 获取身份证号码
    idno = request.POST.get('idno')
    # 获取贷款日期
    loan_date = request.POST.get('loan_date')
    # 获取贷款状态
    state = request.POST.get('state')
    # 获取贷款类型
    dk_type = request.POST.get('dk_type')

    # 定一个字典用于保存前端发送过来的查询条件
    search_dict = dict()
    # 如果有这个值 就写入到字典中去
    if case_order:
      search_dict['loan_id'] = case_order
    if case_name:
      search_dict['name'] = case_name
    if idno:
      search_dict['user_card'] = idno
    if loan_date:
      search_dict['pri_date'] = loan_date
    if state:
      # 通过关联关系查询出来需要的数据
      state_info = StatuTable.objects.filter(statu_name=state).first()

      search_dict['statu_id'] = state_info.statu_id
    if dk_type:
      loa = LoantypeTable.objects.filter(loan_name=dk_type).first()
      search_dict['loa_loan_id'] = loa.loan_id

    # 多条件查询 关键点在这个位置传如的字典前面一定要加上两个星号.
    user_order_info = UserTable.objects.filter(**search_dict)
    # 序列化
    data_info = [user_order.to_dict() for user_order in user_order_info]

    data = {
      'code': 200,
      'data_info': data_info
    }
    return JsonResponse(data)

模型定义(Models)可参考之前的文章,此处不再赘述。

相关模型定义传送门:Model

前端页面与Ajax交互

前端HTML页面结构如下。


<head>
  // 使用jquery就必须引入
	<script src="/static/admin/js/jquery.js" type="text/javascript"></script>
  // 需要使用ajaxSubmit去提交表单就必须引入
  <script src="/static/admin/js/jquery.form.min.js" type="text/javascript"></script>
  // 使用template.js渲染页面就必须引入
  <script src="/static/admin/js/template.js" type="text/javascript"></script>
  <script src="/static/admin/js/order_list.js" type="text/javascript"></script>
</head>

<div class="wrap">
  <div class="page-title">
    <span class="modular fl"><i class="order"></i><em>查询还款案件</em></span>
  </div>
  <div class="operate">
    <form id="search-order">
      {% csrf_token %}
      <div>
        <div style="margin: 10px">
          <label for="">客户单号:</label>
          <input type="text" class="textBox length-long " name="case_order" value=""/>

          <label for="">客户名称:</label>
          <input type="text" class="textBox length-long " name="case_name" value=""/>
        </div>

        <div style="margin: 10px">
          <label for="">身份证号:</label>
          <input type="text" class="textBox length-long " name="idno" value=""/>

          <label for="">贷款日期:</label>
          <input type="text" class="textBox length-long" id="datepicker" name="loan_date" value=""/>
        </div>

        <div style="margin: 10px">
          <label for="">处理状态:</label>
          <select class="inline-select textBox length-long" name="state">
            <option value="未处理">未处理</option>
            <option value="已处理">已处理</option>
          </select>
          <label for="">贷款项目:</label>
          <select class="inline-select textBox length-long" name="dk_type">
            <option value="POS贷">POS贷</option>
            <option value="现金贷">现金贷</option>
          </select>
          <div style="margin-right: 20px;margin-top: 10px;">
            <input type="submit" value="查询" class="tdBtn"/>
          </div>
        </div>
      </div>
    </form>
  </div>

  <table class="list-style Interlaced" id="test">
    <tr>
      <th>申请编号</th>
      <th>客户名称</th>
      <th>联系方式</th>
      <th>身份证号码</th>
      <th>办理日期</th>
      <th>处理人</th>
      <th>处理状态</th>
      <th>处理时间</th>
      <th>操作</th>
    </tr>
    {% verbatim %}
    <script type="text/html" id="tr_list">
      {{ each users as user }}
      <tr>
        <td>
          <input type="checkbox"/>
          <a href="/admin/order_detail/?id={{ user.user_id }}" rel="external nofollow" rel="external nofollow" style="text-decoration:underline; color: blue">
            <span>{{ user.loan_id }}</span>
          </a>
        </td>
        <td class="center">
          <span class="block">{{ user.name }}</span>
        </td>
        <td width="200" style="text-align:center">
          <span class="block">{{ user.phone }}</span>
        </td>
        <td class="center">
          <span>{{ user.card }}</span>
        </td>
        <td class="center">
          <span>{{ user.date }}</span>
        </td>
        <td class="center">
          <span>{{ user.deal_peo }}</span>
        </td>
        <td class="center">
          <span>{{ user.status }}</span>
        </td>
        <td class="center">
          <span>{{ user.deal_time }}</span>
        </td>
        <td class="center">
          <a href="/admin/order_detail/?id={{ user.user_id }}" rel="external nofollow" rel="external nofollow" class="inline-block" title="查看案件"><img
              src="/static/admin/images/icon_view.gif"/></a>
          <a class="inline-block" title="删除案件">
            <img src="/static/admin/images/icon_trash.gif"/>
          </a>
        </td>
      </tr>
      {{ /each }}
    </script>
    {% endverbatim %}
  </table>
  <!-- BatchOperation -->
  <div style="overflow:hidden;">
    <!-- Operation -->
    <div class="BatchOperation fl">
      <input type="checkbox" id="del"/>
      <label for="del" class="btnStyle middle">全选</label>
      <a href="/admin/export_excel/" rel="external nofollow" ><button id="export_excel" type="button" class="btnStyle" >导出excel</button></a>
      <input type="button" value="删除案件" class="btnStyle"/>
    </div>

后端逻辑处理完毕后,即可在前端通过Ajax异步请求获取数据并渲染页面。



$(function () {
  var token = $(':input[name="csrfmiddlewaretoken"]').val()
  $('#search-order').submit(function () {
    $(this).ajaxSubmit({
      url: '/admin/order_list/',
      dataType: 'json',
      type: 'POST',
      headers: {'X-CSRFToken': token},
      success: function (data) {
        if (data.code == 200) {
          var html ='<tr>\n' +
            '      <th>申请编号</th>\n' +
            '      <th>客户名称</th>\n' +
            '      <th>联系方式</th>\n' +
            '      <th>身份证号码</th>\n' +
            '      <th>办理日期</th>\n' +
            '      <th>处理人</th>\n' +
            '      <th>处理状态</th>\n' +
            '      <th>处理时间</th>\n' +
            '      <th>操作</th>\n' +
            '    </tr>'

          var tr_html = template('tr_list', {users: data.data_info})
          html += tr_html
          $('#test').html(html)
        }
      }
    })
    // 阻止默认提交
    return false;
  })
})

总结:

核心难点在于如何构建查询字典,以及如何将构建好的字典正确地作为参数传递给Django的filter方法。

以上关于解决Django中多条件查询问题的全部内容分享到此结束,希望能为读者提供有价值的参考,欢迎继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表