Django ORM中的select_related和prefetch_related有什么区别? [英] What's the difference between select_related and prefetch_related in Django ORM?

查看:440
本文介绍了Django ORM中的select_related和prefetch_related有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django文档中, b
$ b

In Django doc,


select_related()跟随外键关系,当执行它时选择其他相关对象数据查询。

select_related() "follow" foreign-key relationships, selecting additional related-object data when it executes its query.

prefetch_related()对每个关系进行单独的查找,并在Python中加入。

prefetch_related() does a separate lookup for each relationship, and does the ‘joining’ in Python.

加入python是什么意思?有人可以举例说明吗?

What does it mean by "doing the joining in python"? Can someone illustrate with an example?

我的理解是,对于外键关系,请使用select_related;并且对于M2M关系,请使用prefetch_related。这是正确的吗?

My understanding is that for foreign key relationship, use select_related; and for M2M relationship, use prefetch_related. Is this correct?

推荐答案

你的理解大多是正确的。当您要选择的对象是单个对象时,您使用 select_related ,因此 OneToOneField ForeignKey的。您将使用 prefetch_related ,当您将获得集的东西,所以 ManyToManyField 反向 ForeignKey s。只是为了澄清我的意思是reverse ForeignKey s这里是一个例子:

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

区别在于 select_related 执行SQL连接,因此将结果作为表从SQL服务器。另一方面, prefetch_related 执行另一个查询,因此减少了上述示例中的原始对象中的冗余列( ModelA )。您可以使用 prefetch_related 为您可以使用 select_related 的任何内容,因为它通常没有什么意义另一个查询没有通信节省。

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for, it just generally doesn't make much sense since it's another query with no communications savings.

这篇关于Django ORM中的select_related和prefetch_related有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆