简体   繁体   English

Django模型查询是否被缓存?

[英]are django model queries cached?

Let's say I have a model_a that has foreign key to model_b and I am accessing model_b 's properties like so: 假设我有一个model_a ,它具有对model_b外键,并且我正在访问model_b的属性,如下所示:

model_a = ModelA.objects.get(id=id)

x = model_a.model_b.x
y = model_a.model_b.y
z = model_a.model_b.z

Is Django going to the DB and joining the tables to get x , y , and z fields on each line? Django是否要进入数据库并联接表以获取每一行的xyz字段? Or does Django store the result of the first join and then no more joins are needed? 还是Django存储第一个联接的结果,然后不需要更多的联接?

Is this in any way different, performance-wise? 在性能方面,这有什么不同吗?

model_b = model_a.model_b  # only one join
x = model_b.x
y = model_b.y
z = model_b.z

Just curious 只是好奇

You can see the SQL queries that Django with connection.queries . 您可以通过connection.queries 查看 Django 的SQL查询

from django.db import connection
model_a = ModelA.objects.get(id=1)
x = model_a.model_b.x
y = model_a.model_b.y
z = model_a.model_b.z
print(connection.queries)

This should show you two queries, one to fetch model_a and another to fetch model_b . 这应该显示两个查询,一个查询获取model_a ,另一个查询获取model_b Django caches model_a.model_b , so y = model_a.model_b.y model_a.model_b.z do not cause further lookups for model_b . Django会缓存model_a.model_b ,因此y = model_a.model_b.y model_a.model_b.z不会导致对model_b进一步查找。 See the docs on understanding cached attributes for more info. 有关更多信息,请参阅有关了解缓存属性的文档。

You may also find the debug toolbar useful for seeing which SQL queries are running. 您可能还会发现调试工具栏对于查看正在运行的SQL查询很有用。

The most important tools to reduce sql queries are to use select_related and prefetch_related . 减少sql查询的最重要工具是使用select_relatedprefetch_related For your example, you can use select_related . 对于您的示例,可以使用select_related Since you are fetching a single ModelA instance, it will reduce the number of queries from two to one, so it probably won't make a noticeable difference to performance. 由于您正在获取一个ModelA实例,因此它将把查询数量从两个减少到一个,因此它可能不会对性能产生明显的影响。

model_a = ModelA.objects.select_related('model_b').get(id=1)
x = model_a.model_b.x

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

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