What's the difference between select_related and prefetch_related in Django ORM?

2021年11月20日 阅读数:1
这篇文章主要向大家介绍What's the difference between select_related and prefetch_related in Django ORM?,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

问题:

In Django doc,在 Django 文档中,python

select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query. select_related() “遵循”外键关系,在执行查询时选择其余相关对象数据。django

prefetch_related() does a separate lookup for each relationship, and does the "joining" in Python. prefetch_related()对每一个关系进行单独的查找,并在 Python 中进行“链接”。fetch

What does it mean by "doing the joining in python"? “加入python”是什么意思? Can someone illustrate with an example?有人能够举例说明吗?this

My understanding is that for foreign key relationship, use select_related ;个人理解是,对于外键关系,使用select_related and for M2M relationship, use prefetch_related .对于 M2M 关系,请使用prefetch_related Is this correct?这样对吗?url


解决方案:

参考: https://stackoom.com/en/question/274BG