Ad

Get "Foo" Queryset Of ForeignKey Relationships For Initial "Bar" Queryset?

- 1 answer

I have a simple ForeignKey relationship:

class Foo(models.Model):
  id = UUIDField()

class Bar(models.Model):
  id = UUIDField()
  foo = ForeignKey(foo)

If I have an initial queryset of Bar objects, how can I get a queryset of related Foo object for each respective Bar?

I'm currently doing this but I'm wondering if there's a better way:

bar_qs = Bar.objects.all().select_related("foo")

foo_ids = []
for i in bar_qs:
  foo_ids.append(i.foo.id)

foo_qs = Foo.objects.filter(id__in=foo_ids)
Ad

Answer

Try this query:

Foo.objects.filter(bar_set__in=Bar.objects.all())
Ad
source: stackoverflow.com
Ad