在Django中将稀疏数据集显示为表的最有效方法是什么?
我希望在表中显示数据,其中列值(组件)和行(材质)之间存在多对一关系。这些列值和列标题(ComponentTypes)之间还有一种多对一的关系。在我看来,目前我已经实施了类似的措施: 行: 栏目:在Django中将稀疏数据集显示为表的最有效方法是什么?,django,django-templates,django-views,Django,Django Templates,Django Views,我希望在表中显示数据,其中列值(组件)和行(材质)之间存在多对一关系。这些列值和列标题(ComponentTypes)之间还有一种多对一的关系。在我看来,目前我已经实施了类似的措施: 行: 栏目: component_type_list = Components.objects.filter(material__in = materials_list).values("component__name") 按列标题的顺序建立行的值: for material in materials:
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
然后,我将材料和组件类型列表传递到模板,在模板中我有以下内容:
<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>
古鲁ID
物料代码
{组件类型列表%中的组件类型为%
{{component\u type.component\u name}
{%endfor%}
{materials%%中的材质为%s}
{{material.GURU\u ID}
{{material.MATERIALCODE}
{material.component_list_for_table%}
{{component | floatformat}}}%
{%endfor%}
{%endfor%}
即使只有50行(可能约100列),这种操作也非常缓慢。有没有更有效的方法
我对代码进行了编辑以简化它,因此它可能并不完美。我的2美分:
- 使用Django调试工具栏检查您有多少查询,以及它们需要多长时间。你提到“这个操作非常慢”,但有数据是很好的
- 您是否尝试使用
来限制查询prefetch\u related
- 如果SQL太复杂的话,我会使用Python代码(和您一样)来重新组织记录中的数据
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
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