Skip to main content
 首页 » 编程设计

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

2024年12月31日8zhujiabin

这是我的代码:

 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_list 有 100 个模型,这将非常复杂。

我已经试过了:

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 %}