简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM