gpt4 book ai didi

python - 用于计算列计数的不同组合的 Django 对象查询

转载 作者:行者123 更新时间:2023-11-28 16:36:41 25 4
gpt4 key购买 nike

我正在尝试在模板中打印以下结构(伪代码)

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 来形成一些对象的概念。

最佳答案

如果我很好地理解了这个问题,我想你可以通过 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'},
...
]

您可以获得包含列值组合计数的字典。
要呈现结果,您可以创建一个具有颜色大小结构的字典,以便在模板中轻松地对其进行迭代

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>

关于python - 用于计算列计数的不同组合的 Django 对象查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25258755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com