我正在开发一个应用程序来记录一所学校的情况,我正在努力弄清楚每门课程有多少学生。我的应用程序的结构是这样的:
class Course(models.Model):
LEVELS = (
('A0', 'A0'),
('A1', 'A1'),
('B0', 'B0'),
('B1', 'B1'),
('C1', 'C1'),
('C2', 'C2'),
)
name = models.CharField(max_length=32)
level = models.CharField(max_length=2, choices=LEVELS)
class Student(models.Model):
name = models.CharField(max_length=32)
school = models.ForeignKey(School, on_delete=models.CASCADE)
course = models.ManyToManyField(Course)因此,API中的学生看起来如下所示:
[
{
"id": 1,
"name": "Diego",
"school": 2,
"course": [8, 11]
},
{
"id": 2,
"name": "Garry",
"school": 2,
"course": [4]
},
{
"id": 3,
"name": "Dr Henrick",
"school": 2,
"course": [8]
},
]现在,问题出现在我的序列化程序中,在这里,我希望得到每个课程的计数,理想的情况是在这样的dict结构中:
{ 8: 2, 11: 1, 4: 1}我所做的就是从数据库中获取所有的学生,并循环他们的课程列表,但是我想知道我是否可以用Django的查询系统来做类似的事情。
发布于 2021-04-29 00:07:29
您可以在提取所有课程信息之后使用collections.Counter。
from collections import Counter
students = [
{
"id": 1,
"name": "Diego",
"school": 2,
"course": [8]
},
{
"id": 2,
"name": "Garry",
"school": 2,
"course": [1, 8]
},
{
"id": 3,
"name": "Dr Henrick",
"school": 2,
"course": [8]
},
]
print(dict(Counter([course for y in [x["course"] for x in students] for course in y])))输出:
{8: 3, 1: 1} 发布于 2021-04-29 00:45:43
Django的querysets有一个注解法,用于向结果添加聚合。文档中的更多示例。在这种情况下,您需要一组课程的查询,对课程中的学生数量进行注释。
from django.db.models import Count
courses = Course.objects.annotate(student_count=Count('students'))这为您提供了一个当然实例的查询集,每个实例都有一个student_count属性。如果你真的想把它变成course.id: student_count的字典,你可以这样做:
{course.id: course.student_count for course in courses}https://stackoverflow.com/questions/67309341
复制相似问题