Reputation: 39628
I have a model (or actually 2 models, but the other is not that relevant)
class Foo(models.Model):
...
bar = models.ForeignKey(Bar,
...
)
When I have a QuerySet of Foo
:s, how do I get all the Bar
instances that are referenced by that QuerySet?
Since I'm using MySQL, I can't do .distinct(['bar'])
Upvotes: 12
Views: 9949
Reputation: 125
you could use foo_queryset.bar_set.all()
to get all instances of your Bar
foo_queryset = Foo.objects.filter(attr=value)
referenced_bars = foo_queryset.bar_set.all()
The Django documentation has more details.
Upvotes: 1
Reputation: 32304
foo_queryset = Foo.objects.filter(attr=value)
referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id'))
Upvotes: 34