gpt4 book ai didi

python - 使用 for 循环创建多个注释

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:04 24 4
gpt4 key购买 nike

这是我的代码:

 phones = Customer.objects.filter(active=True).values('name')\
.annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[0]))
.annotate(count1 = Count('phone',filter=Q(phone__model__icontains=model_list[1]))
.annotate(count2 = Count('phone',filter=Q(phone__model__icontains=model_list[2]))
.annotate(count3 = Count('phone',filter=Q(phone__model__icontains=model_list[3]))
.annotate(count4 = Count('phone',filter=Q(phone__model__icontains=model_list[4]))
........

html

{% if phones %}
{% for phone in phones %}
<tr>
<td>{{ phone.name }}</td>
<td>{{ phone.count }}</td>
<td>{{ phone.count1 }}</td>
<td>{{ phone.count2 }}</td>
<td>{{ phone.count3 }}</td>
<td>{{ phone.count4 }}</td>
</tr>
{% endfor %}
{% enfif %}

我的 model_list 仍然有很多模型。我应该如何使用 for 循环来简化这些操作?

如果我的 model_list100 个模型,这将非常复杂。

我已经试过了:

for i in range(len(model_list)):
phone= Customer.objects.filter(active=True).values('name')\
.annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[i]))

html

{% if phones %}
{% for phone in phones %}
<tr>
<td>{{ phone.name }}</td>
<td>{{ phone.count }}</td>
</tr>
{% endfor %}
{% endif %}

但是结果不是我想要的,因为我只得到了其中一个数据。例如:model_list[0]

最佳答案

像这样查询计数:

phones = Customer.objects.filter(active=True).values('name')

for idx, model in enumerate(model_list):
counts = {'count%s' % idx : Count('phone',filter=Q(phone__model__icontains=model)}
phones = phones.annotate(**counts)

然后您需要将一系列模型传递给模板(比如在 models_idx_range 中作为上下文参数 models_idx_range=range(models_count))并迭代计数:

{% if phones %}
{% for phone in phones %}
<tr>
<td>{{ phone.name }}</td>
{% for idx in models_idx_range %}
<td>{{ getattr(phone, 'count%s' % idx) }}</td>
</tr>
{% endfor %}
{% endif %}

关于python - 使用 for 循环创建多个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53478595/

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