Vingtoft Vingtoft - 7 months ago 46
Python Question

Django: Filter a QuerySet and select results foreign key

In Django, I have two models:

class A(models.Model):
# lots of fields

class B(models.Model):
a = models.ForeignKey(A)
member = models.BooleanField()

I need to construct a query that filters B and selects all A, something like this:

result = B.objects.filter(member=True).a

Above example code will of course return an error
QuerySet has no attribute 'a'

Expected result:
a QuerySet containing only A objects

Whats the best and fastest way to achieve the desired functionality?


I assume you are looking for something like

result = A.objects.filter(b__member=True)