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

Django使用django-taggit时如何统计用户评论过的博文标签出现次数

解决方案

你当前的查询存在两处问题:

  1. 筛选条件错误:blogpost__user=request.user 匹配的是当前用户发布的博文的标签,和你要的「当前用户评论过的博文」逻辑不符
  2. 缺少聚合统计逻辑,没有用annotate生成计数字段

代码实现

首先导入需要的工具类:

from django.db.models import Count

修改视图函数的查询逻辑:

def examplePage(request):
    # 统计当前用户评论过的博文关联的标签出现次数
    query = Tag.objects.filter(
        blogpost__comment__comment_by=request.user
    ).annotate(
        # 同一篇博文多次评论仅统计1次,符合你给出的示例逻辑
        comment_tag_count = Count('blogpost', distinct=True)
        # 如果需要按实际评论次数统计(同一篇博文评论N次算N次),替换为下面的写法
        # comment_tag_count = Count('blogpost__comment')
    ).order_by('-comment_tag_count')
    
    context = {'tag_stats': query}
    return render(request, 'examplePage.html', context)

模板渲染示例

你可以在examplePage.html中直接遍历查询结果渲染表格:

<table border="1" cellpadding="8">
  <thead>
    <tr>
      <th>标签名称</th>
      <th>关联评论次数</th>
    </tr>
  </thead>
  <tbody>
    {% for tag in tag_stats %}
    <tr>
      <td>{{ tag.name }}</td>
      <td>{{ tag.comment_tag_count }}</td>
    </tr>
    {% empty %}
    <tr>
      <td colspan="2">暂无评论相关标签统计</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

注意:你给出的models.py代码中models.ForeinKey拼写错误,正确写法为models.ForeignKey,请修正后再运行代码避免报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:36:05