简体   繁体   English

Django:如何使用模型实例预取相关对象?

[英]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 = 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. 我该如何像prefetch_related一样立即获取它们。

I think you're looking for select_related . 我认为您正在寻找select_related

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

This will fetch both the b and a instances that were related to it. 这将同时获取b和与其相关的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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