Home > Enterprise >  How to load data from multi-level nesting object
How to load data from multi-level nesting object

Time:05-07

```
when i do the School.objects.filter() query , how to load student object in single 
    query using School.objects.filter()
```
    class School(models.Model):
        name = models.CharField(max_length=50)
        grade = models.ForeignKey(Grade)
    
    class Grade(models.Model):
        name = models.CharField(max_length=10)
        
    class Student(models.Model):
        name = models.CharField(max_length=50)
        grade = models.ForeignKey(Grade)

when i try to load the student object using the school.objects.filter(), its load only school object, when i use select_related('grade'), its load grade object in single sql query how can i use select_related('student'), with school.objects.filter()

CodePudding user response:

Going from Grade to Student is a reverse-ForeignKey relation, which is many-to-one, not one-to-one. You can't do this with select_related.

I'm not absolutely sure but I think you can use prefetch_related:

School.objects.filter(...).prefetch_related( 'grade__students')

CodePudding user response:

you can do something like this:

schools = School.objects.filter(...).prefetch_related('grade__student_set')
for school in schools:
    students_for_school = school.grade.student_set.all()
    print(students_for_school)

One thing to note is that prefetch_related() will make an additional query here, so this will require two queries

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related

  • Related