Django prefetch_related()方法

prefetch_related的作用

prefetch_related()是 Django ORM 中用于优化查询性能的另一个重要方法,尤其在处理多对多(ManyToMany)关系和反向关系时非常有用。它允许你预加载相关对象,从而减少数据库查询次数。

1,创建应用

Test/app13

 python manage.py startapp app13

2,注册应用

Test/Test/settings.py

3,添加应用路由

from django.contrib import admin
from django.urls import path, include

urlpatterns = [

    path('app13/', include('app13.urls')),
]

4,添加模型

Test/app13/models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

class Review(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    rating = models.IntegerField()

 

5,添加视图函数

Test/app13/views.py

from django.shortcuts import render
from .models import Book, Author, Review

def book_list(request):
    # 使用 prefetch_related 预加载作者和评论信息
    books = Book.objects.prefetch_related('authors', 'review_set').all()

    # 准备传递给模板的上下文
    context = {
        'books': books,
    }

    # 渲染并返回响应
    return render(request, '13/book_list.html', context)

 

 6,添加html代码

Test/templates/13/book_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% for book in books %}
    <h2>{{ book.title }}</h2>
    <h3>Authors:</h3>
    <ul>
    {% for author in book.authors.all %}
        <li>{{ author.name }}</li>
    {% endfor %}
    </ul>
    <h3>Reviews:</h3>
    <ul>
    {% for review in book.review_set.all %}
        <li>Rating: {{ review.rating }}</li>
    {% endfor %}
    </ul>
{% endfor %}


</body>
</html>

7,添加路由地址

 Test/app13/urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('book_list/', views.book_list, name='book_list'),
]

 

 8,添加数据

Test/populate_db.py

import random


import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Test.settings')
django.setup()
from app13.models import Author, Book, Review



# 创建随机作者
for _ in range(10):
    author = Author(name=f'Author {_}')
    author.save()

# 创建随机书籍
for _ in range(20):
    book = Book(title=f'Book Title {_}')
    book.save()
    # 随机选择1-3个作者
    authors = Author.objects.all()
    book.authors.set(random.sample(list(authors), random.randint(1, 3)))

# 创建随机评论
for _ in range(50):
    review = Review(
        book=random.choice(Book.objects.all()),
        rating=random.randint(1, 5)
    )
    review.save()

 

 9,访问页面

http://127.0.0.1:8000/app13/book_list/

 

相关推荐

  1. 方 法

    2024-07-16 05:00:03       27 阅读
  2. \__new__()方法

    2024-07-16 05:00:03       47 阅读
  3. QList 方法

    2024-07-16 05:00:03       51 阅读
  4. charCodeAt() 方法

    2024-07-16 05:00:03       60 阅读
  5. ExecuteScalar()方法

    2024-07-16 05:00:03       56 阅读
  6. performClick()方法

    2024-07-16 05:00:03       51 阅读
  7. Go <span style='color:red;'>方法</span>

    Go 方法

    2024-07-16 05:00:03      44 阅读
  8. Go 方法

    2024-07-16 05:00:03       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 05:00:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 05:00:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 05:00:03       57 阅读
  4. Python语言-面向对象

    2024-07-16 05:00:03       68 阅读

热门阅读

  1. Jenkins教程-20-常用插件-Parameterized Trigger

    2024-07-16 05:00:03       22 阅读
  2. Go中的defer看似很简单,实则一点都不难

    2024-07-16 05:00:03       23 阅读
  3. 训练营第十三天 | 二叉树的递归遍历、层序遍历

    2024-07-16 05:00:03       24 阅读
  4. MySQL-字符集(charset)和校对规则(collation)

    2024-07-16 05:00:03       26 阅读
  5. 掌握Eureka:打造高效服务配置中心集成

    2024-07-16 05:00:03       27 阅读
  6. Docker的基本认识和常见命令以及场景介绍

    2024-07-16 05:00:03       21 阅读
  7. Spark和Hadoop作业之间的区别

    2024-07-16 05:00:03       28 阅读
  8. 七大排序算法的Python实现

    2024-07-16 05:00:03       21 阅读