akwataip
akwataip

Reputation: 45

Proper way to access nested foreignkey objects?

I have models with hierarchical relationships:

class School(models.Model):
    name = models.CharField()

class Class(models.Model):
    school = models.ForeignKey(School)

class Student(models.Model):
    class = models.ForeignKey(Class)

And I'd like to retrieve every Student objects related to certain School.
I usually did it like below:

the_school = School.objects.get(name='Springfield Elementary School')
students = Student.objects.filter(class__school=the_school)

But this method needs two models to look up (School and Student) which seems somewhat unnecessary... For me.
So I tried to make a single line query, using Django's built in related manager:

students = School.objects.get(name='...').class_set.student_set.all()
# or 
students = School.objects.get(name='...').class_set.all().student_set.all()

...which did not work.

How can I make a query referencing down from given School object?
Or is there any better solution?

Upvotes: 1

Views: 159

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can use class__school__name as filter argument:

students = Student.objects.filter(class__school__name='Springfield Elementary School''Springfield Elementary School')

Upvotes: 1

Related Questions