练习:假设有以下ORM模型
from django.db import models
class Student(models.Model):
"""学生表"""
name = models.CharField(max_length=100)
gender = models.SmallIntegerField()
class Meta:
db_table = 'student'
class Course(models.Model):
"""课程表"""
name = models.CharField(max_length=100)
teacher = models.ForeignKey("Teacher",on_delete=models.SET_NULL,null=True)
class Meta:
db_table = 'course'
class Score(models.Model):
"""分数表"""
student = models.ForeignKey("Student",on_delete=models.CASCADE)
course = models.ForeignKey("Course",on_delete=models.CASCADE)
number = models.FloatField()
class Meta:
db_table = 'score'
class Teacher(models.Model):
"""老师表"""
name = models.CharField(max_length=100)
class Meta:
db_table = 'teacher'
使用之前学到过的操作实现下面的查询操作:
1.查询平均成绩大于60分的同学的id和平均成绩;
students = Student.objects.annotate(avg_number=Avg('score__number')).filter(avg_number__gt= 60).values('id','avg_number')
# print(students)
for student in students:
print(student['id'],'-',student['avg_number'])
print(students.query)
2.查询所有同学的id、姓名、选课的数量、总成绩;
students = Student.objects.annotate(courses =Count("score__course"),total=Sum("score__number")).values('id','name','courses','total')
print(students)
for student in students:
print('{}-{}-{}-{}'.format(student['id'],student['name'],student['courses'],student['total']))
注:在ORM层面,如果2个表中用到外链相关连,可以不用写 XX_id,直接写 YYY__XX,如上面的代码所示。
3.查询姓“李”的老师的个数;
teachers = Teacher.objects.filter(name__startswith='李').count()
#statrwith 转换后,就是 李%,以什么开始
#endwith 转换后,就是 %李,以什么结尾
print(teachers)
return HttpResponse('demo3')
4.查询没学过“李老师”课的同学的id、姓名;
students = Student.objects.exclude(score__course__teacher__name='李老师').values('id','name')
print(students)
注:多张表关联,通过外键依次关联
5.查询学过课程id为1和2的所有同学的id、姓名;
students = Student.objects.filter(score__course__in=[1,2]).distinct().values('id','name')
print(students)
6.查询所有课程成绩小于60分的同学的id和姓名;
students = Student.objects.filter(score__number__lt=60).distinct().values('id','name')
print(students)
7.查询没有学全所有课的同学的id、姓名;
students = Student.objects.annotate(num = Count(F('score__course'))).filter(num__lt=Course.objects.count()).values('id','name')
print(students)
8.查询所有学生的姓名、平均分,并且按照平均分从高到低排序;
students = Student.objects.annotate(avg=Avg("score__number")).order_by('-avg').values('name','avg')
print(students)
9.查询各科成绩的最高和最低分,以如下形式显示:课程ID,课程名称,最高分,最低分;
courses = Course.objects.annotate(max=Max("score__number"),min=Min("score__number")).values('id','name','max','min')
print(courses)
10.统计总共有多少女生,多少男生;
students = Student.objects.aggregate(male =Count('gender',filter=Q(gender=1)),famele = Count('gender',filter=Q(gender=2)))
print(students)
注:在聚合函数中是可以使用 filter来增加过滤条件的,条件=后的内容,可以用Q表达式来取出,同时 聚合 表达式中也可以用 distinct 来进行去重.
11.将“黄老师”的每一门课程都在原来的基础之上加5分;
scoures = Score.objects.filter(course__teacher__name='黄老师').update(number=F("number")+5)
if scoures:
print('更新成功')
else:
print("更新失败")
注:更新的原则是先查询出来数据,再进行更新操作
12.查询两门以上不及格的同学的id、姓名、以及不及格课程数;
students = Student.objects.annotate(count = Count('score__number',filter=Q(score__number__lt = 60))).filter(count__gte=2).values('id','name','count')
print(students)
13.查询每门课的选课人数;
courses = Course.objects.annotate(count=Count('score__student')).values('name','count')
print(courses)
print(courses.query)