我想在表格中显示数据,其中我的列值(组件)和我的行(材料)之间存在多对一关系。这些列值与列标题(ComponentTypes)之间存在进一步的多对一关系。目前我在我看来已经实现了类似的东西:
行:
materials_list = Materials.objects.all()
列:
component_type_list = Components.objects.filter(material__in = materials_list).values("component__name")
按列标题的顺序建立行的值:
for material in materials:
component_list = []
for component_type in component_type_list:
try:
component = material.components_set.filter(component__name = component_type['component__name'])[0].weight_pct
except:
component = 0
component_list.append(component)
material.component_list_for_table = component_list
然后我将材料和component_type_list传递给我有以下内容的模板:
<table>
<thead>
<tr>
<th>Guru ID</th>
<th>Material</br>Code</th>
{% for component_type in component_type_list %}
<th>{{ component_type.component__name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for material in materials %}
<tr>
<th>{{ material.GURU_ID }}</th>
<th>{{ material.MATERIALCODE }}</th>
{% for component in material.component_list_for_table %}
<td>{{ component|floatformat }}%</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
即使只有50行(可能约100列),这也非常缓慢。有没有更有效的方法呢?
我已经编辑了代码以简化它,因此它可能不完美。
答案 0 :(得分:0)
我的2美分:
prefetch_related
来限制查询?也许是这样的:
materials_list = Materials.objects.prefetch_related('components_set').prefetch_related('components_set__type').all()
for material in material_list:
component_list = []
# your logic here - which should run fast thanks to the prefetches.
material.component_list = component_list