django 聚合統計查詢


from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Sum,Max,Min,Avg
from grade.models import Grade, Student


""" 聚合及統計 """
# 計算張三的期末成績總和
# grade_list = Grade.objects.filter(student_name='張三').aggregate(Sum('score'))
# grade_list = Grade.objects.filter(student_name='張三').aggregate(total = Sum('score'))

# 求語文最高分
# grade_list = Grade.objects.filter(subject_name='語文').aggregate(high_score=Max('score'))
# print(grade_list['high_score'])
# # 最低分
# grade_list = Grade.objects.filter(subject_name='語文').aggregate(min_score=Min('score'))
# print(grade_list['min_score'])

# 平均分
# grade_list = Grade.objects.filter(subject_name='語文').aggregate(avg_score=Avg('score'))
# print(grade_list['avg_score'])

# 統計每個學生的成績總和
# total_list = Grade.objects.values_list('student_name').annotate(Sum('score'))
# for item in total_list:
# print(item)

# user_zhang = Student.objects.get(pk=1)
# list = user_zhang.stu_grade.all()
# for item in list:
# print(item.subject_name,item.score)

user_list = Student.objects.all().annotate(total_score = Sum('stu_grade__score'))
for user in user_list:
print(user.student_name,user.total_score)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM