Django中如何统计指定状态(Installed)的墨盒类型数量?
问题
现有一段代码用于统计每种类型的元素数量,具体代码如下:
Views.py
from django.db.models import Count class HomeView(ListView): model = TypeCartridge template_name = 'home.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) type_counts = TypeCartridge.objects.values('type').annotate(total=Count('type')) context['type_counts'] = type_counts return context
home.html
<div> {% for cartridge in object_list %} <div> <p>Number {{ cartridge.num}}: {{ cartridge.type }}, status {{ cartridge.status }}</p> </div> {% endfor %} <h2>Type Counts</h2> <ul> {% for type_count in type_counts %} <li>{{ type_count.type }} - {{ type_count.total }}</li> {% endfor %} </ul> </div>
示例数据
num type Status 0000001 Samsung Installed 0000002 Samsung NotInstalled 0000003 Xerox Installed 0000004 Brother NotInstalled 0000005 Brother NotInstalled 0000006 Brother NotInstalled 0000007 HP Installed 0000008 HP Installed
当前运行结果
Samsung - 2 Xerox - 1 Brother - 3 HP - 2
现在需要仅统计状态为**"Installed"**的元素,期望结果如下:
Samsung - 1 Xerox - 1 HP - 2
请问如何改进这段代码?
解决方案
只需要在统计前添加过滤条件,筛选出状态为Installed的记录即可,修改Views.py中的type_counts查询语句:
修改后的Views.py代码
from django.db.models import Count class HomeView(ListView): model = TypeCartridge template_name = 'home.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) # 添加filter筛选状态为Installed的记录 type_counts = TypeCartridge.objects.filter(status='Installed').values('type').annotate(total=Count('type')) context['type_counts'] = type_counts return context
说明
- 使用
filter(status='Installed')先过滤出所有状态为已安装的墨盒记录,再对这些记录按type分组并统计数量。 - 模板
home.html无需修改,因为它只是负责渲染统计结果,逻辑修改都在视图层完成。
内容的提问来源于stack exchange,提问作者Nico
相关产品推荐
相关产品推荐

