'Get "Foo" queryset of ForeignKey relationships for initial "Bar" queryset?
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)
Solution 1:[1]
Try this query:
Foo.objects.filter(bar_set__in=Bar.objects.all())
Solution 2:[2]
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.
If a list of foos is ok, you could just do;
bar_qs = Bar.objects.all().select_related("foo")
foos = []
for i in bar_qs:
foos.append(i.foo)
Or you could just start with the foo queryset using;
foo_qs = Bar.objects.select_related('foo').only('foo')
But if you need a bar_qs, then you'd be best doing;
bar_qs = Bar.objects.all().select_related("foo")
foo_qs = bar_qs.only('foo')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RedWheelbarrow |
| Solution 2 |
