Django如何合并两个不同模型Queryset并为查询集新增关联字段
实现步骤
第一步:修改视图函数,关联室外机序列号
你可以先将同客户下的室外机型号和序列号映射为字典,再给室内机查询集的每个对象动态绑定室外机序列号属性,避免N+1查询问题,修改后的视图代码如下:
def clientInventory(request): context = {} client_id = request.GET.get('client_id') id_inven = IndoorInventory.objects.filter(client=client_id) od_inven = OutdoorInventory.objects.filter(client=client_id) # 构造室外机型号-序列号映射字典 od_sr_map = {} for od in od_inven: if od.outdoor_model_no: # 若同一个型号对应多个序列号,可调整为存列表,这里默认取第一个 if od.outdoor_model_no not in od_sr_map: od_sr_map[od.outdoor_model_no] = od.outdoor_sr_no # 给每个室内机对象绑定室外机序列号属性 for invent in id_inven: invent.outdoor_sr_no = od_sr_map.get(invent.outdoor_model_no, '') context['id_inven'] = id_inven return render(request, 'client-inventory.html', context)
第二步:修改模板表格,新增OD SR No列
需要分别修改表头、表尾、表体的结构,新增列展示室外机序列号:
- 先修改thead和tfoot的表头,在
OD Model No列后新增OD SR No列:
<thead> <tr> <th class="filterhead">ID</th> <th class="filterhead">Brand</th> <th class="filterhead">Product/Type</th> <th class="filterhead">ID Model No</th> <th class="filterhead">ID SR No</th> <th class="filterhead">OD Model No</th> <!-- 新增列 --> <th class="filterhead">OD SR No</th> <th class="filterhead">Actions</th> </tr> <tr> <th>ID</th> <th>Brand</th> <th>Product/Type</th> <th>ID Model No</th> <th>ID SR No</th> <th>OD Model No</th> <!-- 新增列 --> <th>OD SR No</th> <th>Actions</th> </tr> </thead> <tfoot> <tr> <th>ID</th> <th>Brand</th> <th>Product/Type</th> <th>ID Model No</th> <th>ID SR No</th> <th>OD Model No</th> <!-- 新增列 --> <th>OD SR No</th> <th>Actions</th> </tr> </tfoot>
- 再修改tbody的两行模板(正常行和告警行),在
OD Model No的td后新增展示序列号的td:
<!-- 告警行bg-danger部分 --> <tr class="bg-danger"> <td>{{ invent.id }}</td> <td>{{ invent.indoor_brand }}</td> <td>{{ invent.product }}</td> <td>{{ invent.indoor_model_no }}</td> <td>{{ invent.indoor_sr_no }}</td> <td>{{ invent.outdoor_model_no }}</td> <!-- 新增列 --> <td>{{ invent.outdoor_sr_no }}</td> <td> <!-- 原有操作按钮代码不变 --> </td> </tr> <!-- 正常行部分 --> <tr> <td>{{ invent.id }}</td> <td>{{ invent.indoor_brand }}</td> <td>{{ invent.product }}</td> <td>{{ invent.indoor_model_no }}</td> <td>{{ invent.indoor_sr_no }}</td> <td>{{ invent.outdoor_model_no }}</td> <!-- 新增列 --> <td>{{ invent.outdoor_sr_no }}</td> <td> <!-- 原有操作按钮代码不变 --> </td> </tr>
内容的提问来源于stack exchange,提问作者Armaan usman
相关产品推荐
相关产品推荐

