Django ORM统计ReadingHistory表平均阅读量时计数错误如何解决
问题根因
你当前的计算逻辑错误出现在分母取值上:
- 你原本用
Count('student_list_class__child__child_reading_history')统计的是ReadingHistory表的行数,也就是学生+书籍的配对记录总数 - 预期的分母应该是当前班级的学生总人数
修复方案
直接修改get_avg_read_book方法即可,优化后逻辑如下:
from django.db.models import Sum def get_avg_read_book(self, obj): # 计算班级所有学生的总阅读量,无阅读记录时兜底为0 sum_result = obj.student_list_class.aggregate( total_read=Sum('child__child_reading_history__counter') ) total_read = sum_result['total_read'] or 0 # 计算班级总学生数 total_student = obj.student_list_class.count() # 避免除以0报错 if total_student == 0: return 0 # 可根据需求调整小数保留位数,比如round(total_read / total_student, 2) return total_read / total_student
逻辑说明
- 直接通过当前传入的
Class实例obj的反向关联student_list_class查询,不需要再重新过滤Class表,减少一次不必要的数据库查询 - 分母取
student_list_class的计数,就是班级真实的学生总人数,符合你预期的计算规则 - 增加了空值和除0防护,避免班级没有学生或者没有阅读记录时抛出异常
内容的提问来源于stack exchange,提问作者ATK
相关产品推荐
相关产品推荐

