How to reverse query objects for multiple levels in django?

735 views Asked by At

Suppose I have:

Class Level1:
    name = CharField()

Class Level2:
    name = CharField()
    level1 = ForeignKey(Level1)

Class Level3:
    name = CharField()
    level2 = ForeignKey(Level2)

Class Level4:
    name = CharField()
    level3 = ForeignKey(Level3)

Suppose I already have an Level1 object: level1, how can get all Level4 objects of Level1?

Like the meaning: level1.level2_set.level3_set.level4_set.

2

There are 2 answers

0
Daniel Roseman On BEST ANSWER

You start with the model whose objects you want to get, Level4, then follow the relationships with the double-underscore syntax.

Level4.objects.filter(level3__level2__level1=my_level1_object)
0
Adrian Ghiuta On

Based on the docs, I'd use:

Level4.objects.filter(name="...", level3__name="...", level3__level2__name="...", level3__level2__level1__name="...")