Home > Blockchain >  Get "Foo" queryset of ForeignKey relationships for initial "Bar" queryset?
Get "Foo" queryset of ForeignKey relationships for initial "Bar" queryset?

Time:03-28

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)

CodePudding user response:

Try this query:

Foo.objects.filter(bar_set__in=Bar.objects.all())

CodePudding user response:

You're doing the right thing in using select_related because that gathers the related foo object in the same query so there's no need to query the database again for the Foo table.

You could just do;

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

foos = []
for i in bar_qs:
    foos.append(i.foo)
  • Related