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

如何在Django中对用户Award外键关联的Nomination投票数求和

解决方案

第一步:导入聚合函数

首先在views.py顶部导入Django的聚合函数Sum:

from django.db.models import Sum

第二步:修正视图查询逻辑

你原有代码存在字段名大小写错误、ORM语法错误、聚合字段错误的问题,修正后的DashboardView代码如下:

@method_decorator([login_required], name='dispatch')
class DashboardView(TemplateView):
    template_name = 'admin/Dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 直接在查询奖项的时候注解总投票数,每个奖项对象自带总票数属性
        context['user_awards'] = Award.objects.filter(
            admin=self.request.user  # 注意模型字段是小写admin,原来的大写Admin会报错
        ).annotate(
            # 跨关联关系聚合所有提名的votes总和,双下划线是Django ORM跨表查询的标准语法
            total_votes=Sum('category__nomination__votes')
        ).order_by('-date')
        return context

第三步:模板中使用

直接遍历user_awards即可同时获取奖项信息和对应的总投票数,空数据场景下默认显示0:

{% for award in user_awards %}
<div class="award-item">
    <h3>{{ award.name }}</h3>
    <p>总投票数:{{ award.total_votes|default:0 }}</p>
</div>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:36:03