I have:
class Teacher(models.Model):
name = models.CharField(...)
...
class Student(models.Model):
age = models.IntegerField(...)
teacher = models.ForeignKey(Teacher, ...)
...
I have a queryset of teachers:
teachers = Teacher.objects.filter(name="Betty")
I want to find all of the students related to each teacher in that queryset, and I need the result to be grouped by teacher. Something like:
{
<Teacher: 1>: [<Student: 1>, <Student: 2>],
<Teacher: 2>: [<Student: 3>, <Student: 4>]
}
I could accomplish this by just looping over every object in the teachers
queryset and filtering Students by students that ForeignKey to that teacher, but that seems really slow and would require an additional DB call for each object. Is there any way to accomplish this in just one or a few DB calls, ideally while staying Python-only and not resorting to SQL?