Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse query objects for multiple levels in django?

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.

like image 814
dspjm Avatar asked Jun 05 '15 06:06

dspjm


1 Answers

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)
like image 53
Daniel Roseman Avatar answered Sep 19 '22 17:09

Daniel Roseman