Django对象查询以统计不同列数的组合
我想在模板中打印出以下结构(伪代码)
class Car():
field color
field size
其中,Column1和Column2代表同一个表的不同列(对象的字段),而值则是这个列可能拥有的值。
我该如何在模板中打印这个内容呢?
red orange blue
small 123 4 45
regular 34 64 54
large 64 34 23
我知道怎么构建表格,但对于django查询和SQL来形成某个对象的概念我还不太熟悉。
2 个回答
0
在数据库中没有直接的方法,你应该这样做:
1. 先用这个命令:select count(1) count, size, color from car group by size, color
这样会返回类似下面的结果:
count size color
2 small red
4 small orange
2. 然后根据大小和颜色来展示这些结果。
4
如果我理解得没错,问题的意思是你可以用 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>