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

I have a model (or actually 2 models, but the other does not fit)

class Foo(models.Model): ... bar = models.ForeignKey(Bar, ... ) 

When I have a QuerySet from Foo : s, how do I get all Bar instances referenced by this QuerySet?

Since I use MySQL, I can not do .distinct(['bar'])

+6
source share
2 answers
 foo_queryset = Foo.objects.filter(attr=value) referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id')) 
+18
source
 bars = Bar.objects.filter(foo_set__attr=value) 
0
source

Source: https://habr.com/ru/post/926304/


All Articles