Vingtoft
Vingtoft

Reputation: 14586

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?

Upvotes: 1

Views: 1429

Answers (3)

Anand Pujari
Anand Pujari

Reputation: 9

Below code will not filter everything but it will filter all the values with respect to field, might be you are looking for same

B.objects.filter(member=True).filter(a__somefield='some value')

Upvotes: 0

marcusshep
marcusshep

Reputation: 1964

An alternative to Andrey Zarubin's answer would be to iterate over the queryset you had and create a list of a objects.

b_objects = B.objects.filter(member=True)
a_objects = [result.a for result in b_objects]

Upvotes: 2

Andrii Zarubin
Andrii Zarubin

Reputation: 2245

I assume you are looking for something like

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

Upvotes: 7

Related Questions