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

如何用Django Annotate为User模型标注最频繁投票瞳色字段?

实现方案

要实现为User模型标注eyesColorMostFreq字段的需求,我们可以通过Django ORM的聚合函数、子查询和条件表达式完成,具体步骤如下:

1. 导入所需ORM工具

首先引入需要的模型和函数:

from django.db.models import Count, Exists, OuterRef, Value, IntegerField
from django.db.models.functions import Coalesce

2. 构建投票统计子查询

为每个用户统计被投票的瞳色数据,同时标记该瞳色是否包含用户自投票:

# 子查询:统计每个用户(dstID)的各瞳色投票数,标记是否有自投票
vote_stats = Survey.objects.filter(dstID=OuterRef('pk')).values('eyesColor').annotate(
    # 统计该瞳色的总投票数
    vote_count=Count('eyesColor'),
    # 判断该瞳色是否存在用户自投记录
    has_self_vote=Exists(
        Survey.objects.filter(
            dstID=OuterRef('dstID'),
            eyesColor=OuterRef('eyesColor'),
            srcID=OuterRef('dstID')  # srcID与dstID一致即为自投
        )
    )
).order_by(
    '-vote_count',  # 优先按投票数降序
    '-has_self_vote'  # 投票数相同时,有自投的瞳色优先排序
)

3. 标注目标字段

用Subquery获取排序后的首个瞳色,通过Coalesce处理无投票记录的情况:

# 为User模型标注eyesColorMostFreq字段
users_with_eye_color = User.objects.annotate(
    eyesColorMostFreq=Coalesce(
        Subquery(vote_stats.values('eyesColor')[:1]),  # 取排序后的第一个瞳色
        Value(0),  # 无投票记录时返回0
        output_field=IntegerField()
    )
)

逻辑说明

  • 无投票记录:Coalesce会将空的子查询结果替换为0;
  • 单瞳色得票最高:直接返回该瞳色;
  • 多瞳色得票相同:若包含用户自投票,会优先选中该自投瞳色;
  • 多瞳色得票相同且无自投:返回排序后的首个瞳色,可在order_by后追加'eyesColor'来固定顺序,比如'-vote_count', '-has_self_vote', 'eyesColor'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:50:31