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

如何在Django中向作者展示其帖子的月度获赞总数

Django按月份统计作者帖子获赞总数方案

问题分析

你当前的视图代码仅能统计作者的帖子总数,无法实现按月份聚合所有帖子的获赞总数需求。结合你提供的blogs模型,我们可以通过Django的ORM聚合功能实现分组统计。

修正与实现步骤

1. 修复原视图中的模型引用错误

原total_contents方法里误用了post.objects,而你的模型类是blogs,先修正这个基础问题:

def total_contents(self):
    # 修正模型引用为blogs
    total_posts = blogs.objects.filter(author=self.request.user).count()
    return total_posts

2. 添加月度获赞统计方法

在视图类中新增方法,利用ORM的annotate和聚合函数按年份+月份分组,避免跨年的月份数据混淆:

from django.db.models import Sum, ExtractMonth, ExtractYear

def monthly_likes_summary(self):
    # 筛选当前用户的帖子,按年、月分组并求和获赞数
    monthly_stats = blogs.objects.filter(author=self.request.user).annotate(
        # 提取创建日期的年份和月份
        post_year=ExtractYear('created_on'),
        post_month=ExtractMonth('created_on')
    ).values('post_year', 'post_month').annotate(
        # 对每组的like_count求和
        total_month_likes=Sum('like_count')
    ).order_by('post_year', 'post_month')
    
    # 转换为易读的键值对格式(如"2024年3月": 150)
    formatted_stats = {}
    for stat in monthly_stats:
        month_key = f"{stat['post_year']}年{stat['post_month']}月"
        formatted_stats[month_key] = stat['total_month_likes']
    return formatted_stats

3. 将统计数据传入模板上下文

修改get_context_data方法,把月度获赞统计数据加入上下文:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['total_contents'] = self.total_contents()
    # 新增月度获赞数据
    context['monthly_likes'] = self.monthly_likes_summary()
    return context

4. 模板中展示统计结果

在你的模板文件中遍历monthly_likes数据,按需求格式展示:

{% for month, total_likes in monthly_likes.items %}
    <p>{{ month }}获赞总数为{{ total_likes }}</p>
{% empty %}
    <p>暂无获赞数据</p>
{% endfor %}

补充说明

  • 如果你更倾向于直接统计likes多对多关系的实际数量(而非依赖like_count字段),可以把Sum('like_count')替换为Count('likes'),但注意这种方式会触发关联查询,性能略低于直接使用预存的like_count。
  • ExtractMonth和ExtractYear需要数据库支持,主流数据库(MySQL、PostgreSQL、SQLite3.31+)均兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:55:21