使用外键的 Django 多个查询

Django multiple queries with foreign keys

假设我有两个不同的应用程序:

teacher/models.py:

  Teacher(models.Model):
     name = models.CharField(max_length=300)


class/models.py:

  Class(models.Model):
     name = models.CharField(max_length=300)
     teacher = models.ForeignKey(Teacher)
     students = models.ManyToManyField(Student)

我想得到所有带 类 和所有 类 的老师。

我想要的结果:

{[
   teacher: '3L' #Teachers Id
   classes: ['20L','14L','30L'] #list of Class objects or ids with the above teacher
],
[# similar to above]

}

这可以吗?这就是我目前正在做的事情:

classes = Class.objects.all()
teachers = Teacher.objects.filter(id__in=classes.value_list('teacher',flat=True).distinct())
for teacher in teachers:
    classes_for_teachers = classes.objects.filter(teacher=teacher)

在上面的代码中,有四个查询是用循环进行的,这肯定会增加时间复杂度。有更好的解决方案吗?提前致谢。

使用prefetch_related:

teachers = Teacher.objects.prefetch_related('class_set')

# what you want is not a valid Python structure (set of lists (looking like dicts))
# list of dicts makes more sense
result = [
    {'teacher': t.pk, 'classes': t.class_set.all()}
    for t in teachers
]

无论有多少教师和 类,这只会触发 2 个数据库查询。