当前位置: 首页 > article >正文

Django一分钟:使用prefetch_related避免陷入大量的查询中导致严重的性能问题

本文将通过简单的示例介绍为什么要使用prefetch_related

准备工作

创建模型

from django.db import models

class Product(models.Model):
    product_name = models.CharField(max_length=255)

class Component(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='components')
    code = models.CharField(max_length=255)

    class Meta:
        ordering = ['product']

创建数据

>>> from api.models import Product
>>> p1 = Product.objects.create(product_name="产品1")
>>> p2 = Product.objects.create(product_name="产品2")
>>> from api.models import Component
>>> pc1 = Component.objects.create(product=p1, code="LS")
>>> pc2 = Component.objects.create(product=p1, code="LM")
>>> pc3 = Component.objects.create(product=p2, code="XYB")
>>> pc4 = Component.objects.create(product=p2, code="LXC")

settings.py文件中添加配置输出运行时执行的sql

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}

不使用prefetch_related

from api.models import Product
ps = Product.objects.all()
# SELECT "api_product"."id", "api_product"."product_name" FROM "api_product"; args=(); alias=default
    
for p in ps:
    print(p.components.all())
    
# SELECT "api_component"."id", "api_component"."product_id", "api_component"."code" FROM "api_component" WHERE "api_component"."product_id" = 1 ORDER BY "api_component"."product_id" ASC LIMIT 21; args=(1,);

# SELECT "api_component"."id", "api_component"."product_id", "api_component"."code" FROM "api_component" WHERE "api_component"."product_id" = 2 ORDER BY "api_component"."product_id" ASC LIMIT 21; args=(2,);

不使用prefetch_related我们获取所有"产品"执行了一次sql查询,然而当我们遍历想要获取所有产品的组件时,对每个产品都执行了一次sql查询。

我们的示例中只产品的数量只有两个,当产品的数量非常多,成百上千时,对每个产品你都要到数据库执行一次查询,这将导致严重的性能问题,也就是所谓的n+1问题。

使用prefetch_related

from api.models import Product
ps = Product.objects.prefetch_related("components")
# SELECT "api_product"."id", "api_product"."product_name" FROM "api_product"; args=(); alias=default

# SELECT "api_component"."id", "api_component"."product_id", "api_component"."code" FROM "api_component" WHERE "api_component"."product_id" IN (1, 2) ORDER BY "api_component"."product_id" ASC; args=(1, 2); alias=default
for p in ps:
    print(p.components.all())

可以清晰的看到总共执行了两次sql查询,在获取全部"产品"的时候通过一次额外的查询将所有产品的组件信息缓存起来,当我们需要的时候是从缓存中获取,不会执行任何的数据库查询

select_related

select_related只能用于一对一关系和外键关系,它是利用Join只进行一次SQL查询,但是它的局限也很明显,不能用于多对多,多对一等

from api.models import Component
c = Component.objects.select_related("product").get(pk=1)

# SELECT "api_component"."id", "api_component"."product_id", "api_component"."code", "api_product"."id", "api_product"."product_name" FROM "api_component" INNER JOIN "api_product" ON ("api_component"."product_id" = "api_product"."id") WHERE "api_component"."id" = 1 LIMIT 21; args=(1,); alias=default

http://www.kler.cn/news/328873.html

相关文章:

  • WebGL深究:动画与交互 —— 赋予虚拟世界生命与灵魂
  • YOLOv11尝鲜测试五分钟极简配置
  • SpringBoot整合JPA详解
  • 工控系统组成与安全需求分析
  • leetcode每日一题day21(24.10.1)——最低票价
  • Street View Synthesis with Gaussian Splatting and Diffusion Prior 学习笔记
  • 【Java SE 题库】移除元素(暴力解法)--力扣
  • 室内定位论文整理-20240925期
  • 计算机毕业设计党建学习网站查看发布党建评论留言搜索部署安装/springboot/javaWEB/J2EE/MYSQL数据库/vue前后分离小程序
  • 【SpringCloud】多机部署, 负载均衡-LoadBalance
  • 使用 Seaborn 热图的 5 种方法(Python 教程)
  • Vue+Flask
  • Pencils Protocol 全面推动市场,生态通证 DAPP 将持续通缩
  • 【数据结构初阶】排序算法(下)冒泡排序与归并排序
  • Jupyter Notebook 产生 jupyter_notebook_config.py 配置文件
  • Html jquery下拉select美化插件——selectFilter.js
  • C++网络编程之IP地址和端口
  • 看似容易赚钱的炒股真的赚钱吗
  • 行为设计模式 -模板方法模式- JAVA
  • 计算机毕业设计 养老院管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • 59 双向循环神经网络_by《李沐:动手学深度学习v2》pytorch版
  • 在2核2G服务器安装部署MySQL数据库可以稳定运行吗?
  • 武汉正向科技格雷母线公司,无人天车系统,采用格雷母线定位技术
  • 如何排查 Windows 无法连接ubuntu远程服务器
  • ScrapeGraphAI 大模型增强的网络爬虫
  • “Xian”(籼)和“Geng”(粳)米怎么读?
  • 戴尔电脑怎么开启vt虚拟化_戴尔电脑新旧机型开启vt虚拟化教程
  • ROS学习笔记(三):VSCode集成开发环境快速安装,以及常用扩展插件配置
  • 推荐 uniapp 相对好用的海报生成插件
  • Socket【C#】Demo