0

Let's say I have the models Foo, Bar and FooBar. Bar has a ForeignKey reference to Foo. FooBar has a ForeignKey reference to Bar. Given a Foo-object, how do I most efficiently gather all related FooBar objects? I don't like using this:

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

1 Answers1

1

Simply do it by spanning relationship

foobars = FooBar.object.filter(bar__foo=foo)
iklinac
  • 14,944
  • 4
  • 28
  • 30