Django 聚合外键层次结构

Django aggregate ForeignKey hierarchy

假设我有模型 FooBarFooBarBar 具有对 Foo 的外键引用。 FooBar 具有对 Bar 的外键引用。给定一个 Foo 对象,我如何最有效地收集所有相关的 FooBar 对象?我不喜欢用这个:

foobars = []
for bar in foo.bar_set.all():
    for foobar in bar.foobar_set.all():
        foobars.append(foobar)

跨越关系就可以了

foobars = FooBar.object.filter(bar__foo=foo)