dspjm
dspjm

Reputation: 5850

Django: How to prefetch related object with model instance?

ClassA:
 ...

ClassB:
    ForeignKey(A)

ClassC:
    ForeignKey(B)

now I have a instance of C.

c = C()
b = c.b
a = b.a

This way, the db will be visited for three times.

How can I let them be fetched at once like prefetch_related.

Upvotes: 0

Views: 804

Answers (1)

schillingt
schillingt

Reputation: 13731

I think you're looking for select_related.

c = C.objects.select_related('b__a').get()

This will fetch both the b and a instances that were related to it.

Upvotes: 1

Related Questions