Django对象查询以计算列计数的不同组合

4
我将尝试在模板中打印以下结构(伪代码):
class Car():
    field color
    field size

其中Column1和Column2代表同一张表的不同列(对象的字段),values是该列可能拥有的值。

如何将此打印到模板中?

            red       orange        blue
small       123         4           45
regular     34          64          54
large       64          34          23

我知道如何建立表格,但是 django 查询和将其作为 SQL 形式来形成某些对象的概念我不熟悉。


1
这个太抽象了,请展示一些模型。 - Daniel Roseman
增加了一个更加现实的例子。 - Capuchin
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>

如何在模板中迭代结果? - Capuchin
<td class="value">{{ combinations_dict.color.size}}</td> 这段代码不知道为什么无法工作。 - Capuchin

0

数据库中没有直接的方法,你需要做的是:
1. 使用 group by 按 size 和 color 分组,选择 count(1) count, size, color,将返回类似以下结果:
count size color
2 small red
4 small orange

2. 根据 size/color 渲染结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接