Kimvais
Kimvais

Reputation: 39628

How to get a django QuerySet of all ForeignKeys of all objects in a Queryset

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

Answers (3)

Davi Wesley
Davi Wesley

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

schacki
schacki

Reputation: 9533

bars = Bar.objects.filter(foo_set__attr=value)

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32304

foo_queryset = Foo.objects.filter(attr=value)
referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id'))

Upvotes: 34

Related Questions