Python Django对象查询,用于计算列计数的不同组合
我试图在模板中打印以下结构(伪代码) 其中,Column1和Column2表示同一表的不同列(对象字段),值是该列可能具有的值 如何将此打印到模板Python Django对象查询,用于计算列计数的不同组合,python,django,orm,Python,Django,Orm,我试图在模板中打印以下结构(伪代码) 其中,Column1和Column2表示同一表的不同列(对象字段),值是该列可能具有的值 如何将此打印到模板 red orange blue small 123 4 45 regular 34 64 54 large 64 34 23 我知道如何构建表,但django查
red orange blue
small 123 4 45
regular 34 64 54
large 64 34 23
我知道如何构建表,但django查询的概念以及作为SQL形成一些我不熟悉的对象。在数据库上没有直接的方法,您应该做的是:
1.按大小、颜色从车辆组中选择计数(1)计数、大小、颜色
将返回类似于
的内容 计数大小颜色
2个小红色
4个小橙色
2.按大小/颜色呈现结果如果我很好地理解了这个问题,我想你可以通过django group by approach来完成
>>>>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'},
...
]
您可以获得包含列值组合计数的dict要呈现结果,可以创建具有颜色大小结构的dict,以便在模板中轻松迭代
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>
/td>
{%表示颜色大小,颜色为%}
{{compositions_dict.color.size}
{%endfor%}
{%表示大小,单位为%}
{{size}}
{%表示颜色,大小以组合形式显示。\u dict.items%}
{%表示当前大小,val表示大小。items%}
{%if size==curr\u size%}
{{val}}
{%endif%}
{%endfor%}
{%endfor%}
{%endfor%}
这太抽象了。请显示一些模型。添加了一个更真实的示例如何在模板中迭代结果?{{combinations_dict.color.size}不知何故不起作用
<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>