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

Django:统计单个SoundItem实例评论中最频繁的分类

统计SoundItem评论中最频繁的分类(无需手动遍历)

可以直接通过Django ORM的聚合查询实现,避免手动遍历评论统计,代码如下:

from django.db.models import Count

# 假设s是已获取的SoundItem实例
category_stats = SoundCategory.objects.filter(
    sound_reviews__sound=s
).annotate(
    occurrence_count=Count('sound_reviews')
).order_by('-occurrence_count')

# 转换为目标字典格式
result = {category.name: category.occurrence_count for category in category_stats}

代码说明:

  • filter(sound_reviews__sound=s):筛选出所有被当前SoundItem的评论关联的分类,利用SoundCategory与SoundItemReview的反向关联sound_reviews完成跨表过滤
  • annotate(occurrence_count=Count('sound_reviews')):为每个分类添加统计字段occurrence_count,统计该分类被多少条评论关联(对应示例中分类的出现次数)
  • order_by('-occurrence_count'):按出现次数降序排列,最频繁的分类会排在结果最前面
  • 最后通过字典推导式将查询结果转换为你需要的{分类名称: 出现次数}格式

针对你给出的示例场景,这段代码会返回{"category2": 2, "category1": 1, "category3": 1},完全符合预期。

如果需要包含所有分类(即使未被当前SoundItem的评论关联,次数记为0),可以调整为以下写法:

from django.db.models import Count, Q

category_stats = SoundCategory.objects.all().annotate(
    occurrence_count=Count('sound_reviews', filter=Q(sound_reviews__sound=s))
).order_by('-occurrence_count')

result = {category.name: category.occurrence_count for category in category_stats}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:37:26