You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中统计各status分类元素数量并在页面展示?

实现Status统计展示的解决方案

需求说明

你需要在HTML页面中展示每个status对应的Application元素总数,示例数据的期望展示结果为:

accepted - 4
denied - 2
in process - 1

现有代码

home.html模板

<div class="headtext">
    <form method="GET" action="{% url 'search' %}">
        <input type="search" type="text" name="q" required placeholder="Put appnumber">
        <button type="submit">Find</button>
    </form>
</div>
<div>
  {% for application in object_list %}
        <div>
            <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p>
        </div>
  {% endfor %}
</div>

views.py视图

class HomeView(ListView):
    model = Application
    template_name = 'home.html'

class Search(ListView):
    template_name = 'home.html'
    def get_queryset(self):
        return Application.objects.filter(appnumber__icontains=self.request.GET.get("q"))
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["q"] = self.request.GET.get("q")
        return context

实现步骤

1. 修改视图,添加状态统计逻辑

需要在HomeView和Search视图中,通过Django的ORM分组统计各status的数量,并将统计结果传入模板上下文。

首先导入Count函数:

from django.db.models import Count

然后修改两个视图的get_context_data方法:

HomeView修改后

class HomeView(ListView):
    model = Application
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 按status分组统计数量,按数量降序排序
        context['status_counts'] = Application.objects.values('status').annotate(count=Count('id')).order_by('-count')
        return context

SearchView修改后

class Search(ListView):
    template_name = 'home.html'
    
    def get_queryset(self):
        query = self.request.GET.get("q", "")
        return Application.objects.filter(appnumber__icontains=query)
    
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        query = self.request.GET.get("q", "")
        context["q"] = query
        
        # 基于搜索过滤后的结果统计status数量
        filtered_queryset = self.get_queryset()
        context['status_counts'] = filtered_queryset.values('status').annotate(count=Count('id')).order_by('-count')
        return context

2. 在模板中添加统计展示

在home.html中合适的位置(比如表单下方)添加统计展示的代码:

<div class="status-stats">
    <h3>状态统计</h3>
    {% if status_counts %}
        {% for stat in status_counts %}
            <p>{{ stat.status }} - {{ stat.count }}</p>
        {% endfor %}
    {% else %}
        <p>暂无相关数据</p>
    {% endif %}
</div>

说明

  • values('status'):指定按status字段分组
  • annotate(count=Count('id')):统计每组内的记录数量,用count字段存储结果
  • order_by('-count'):按统计数量从多到少排序,若不需要排序可删除此部分
  • 搜索视图中基于filtered_queryset统计,保证搜索后的统计结果是过滤后的数量

内容的提问来源于stack exchange,提问作者Stew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:35:16