这是我的代码:
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]
答案 0 :(得分:1)
执行以下操作以查询计数:
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 %}
答案 1 :(得分:0)
我不是django专家,但我认为这是您的错误:
phone = Customer.objects.filter(active=True).values('name')
for i in range(len(model_list)):
phone= phone.annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[i]))
您始终使用for循环中的最后一个值覆盖电话
答案 2 :(得分:0)
尝试这个
phones = Customer.objects.filter(active=True).values('name')\
.annotate(count = Count('phone',filter=Q(phone__model__icontains=[i for i in model_list]))