如果我理解问题正确的话,我认为您可以使用Django分组方法来实现。
>>>>from your_app import models
>>>>from django.db.models import Count, Avg
>>>>combinations_dict_list = models.Car.objects.values('color', 'size').order_by().annotate(Count('color'), Count('size'))
>>>>combinations_dict_list
[{'color__count': 1, 'size__count': 1, 'color': 'red', 'size': 'small'},
{'color__count': 2, 'size__count': 2, 'color': 'red', 'size': 'regular'},
{'color__count': 3 'size__count': 3, 'color': 'red', 'size': 'large'},
...
]
你可以获取一个包含列值组合计数的字典。
为了呈现结果,你可以创建一个颜色-尺寸结构的字典,在模板中轻松迭代它。
combinations_dict = {}
for comb in combinations_dict_list:
if not combinations_dict.get(comb['color'], {}):
combinations_dict[comb['color']] = {}
if not combinations_dict[comb['color']].get(comb['size'], {}):
combinations_dict[comb['color']][comb['size']] = {}
combinations_dict[comb['color']][comb['size']] = comb['color__count']
colors = combinations_dict.keys()
sizes = combinations_dict[colors[0]].keys()
模板代码
<table>
<tr><td>/td>
{% for color size in colors %}
<td class="color_header">{{ combinations_dict.color.size}}</td>
{% endfor %}
</tr>
{% for size in sizes %}
<tr>
<td class="size_header">{{ size }}</td>
{% for color, sizes in combinations_dict.items %}
{% for curr_size, val in sizes.items %}
{% if size == curr_size %}
<td class="value">{{ val}}</td>
{% endif %}
{% endfor %}
{% endfor %}
</tr>
{% endfor %}
</table>