Django中关联ManyToManyField时单DB查询实现及优化问询
问题2:单次查询获取学生姓名与科目数量
用annotate结合Count聚合函数即可实现,一次查询拿到两个数据:
from django.db.models import Count student_data = Student.objects.filter(pk=student_id).annotate( subject_count=Count('subjects') ).values('name', 'subject_count').first() if student_data: print(student_data['name']) print(student_data['subject_count'])
原理
Count('subjects')会在查询学生时,自动左连接多对多关联表,聚合出该学生的科目总数,整个过程由数据库一次性完成,避免了原方案中student.subjects.count()触发的第二次查询。
内容的提问来源于stack exchange,提问作者Baz
相关产品推荐
相关产品推荐

