Django select_related()方法

select_related()的作用

select_related()是Django ORM(对象关系映射)中的一种查询优化方法,主要用于减少数据库查询次数,提高查询效率。当你在查询一个模型实例时,如果这个实例有ForeignKey关联到其他模型,那么select_related()可以帮助你在一次数据库查询中同时获取到这些关联模型的数据。

1,创建应用

Test/app12

复制代码
python manage.py startapp app12

2,注册应用

Test/Test/settings.py

3,添加应用路由

Test/Test/urls.py

复制代码
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('app12/', include('app12.urls')),
]

4,添加模型

Test/app12/models.py

复制代码
# models.py
from django.db import models

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

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

5,添加视图函数

Test/app12/views.py

复制代码
# views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.select_related('author').all()
    return render(request, '12/post_list.html', {'posts': posts})

6,添加html代码

Test/templates/12/post_list.html

复制代码
<!-- post_list.html -->
{% for post in posts %}
    <h2>{{ post.title }}</h2>
    <p>By: {{ post.author.name }}</p>
    <p>{{ post.content }}</p>
{% endfor %}

7,添加路由地址

复制代码
from django.urls import path
from . import views

urlpatterns = [

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

8,添加数据

Test/add_data.py

复制代码
import os
import django
import random
from faker import Faker

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Test.settings")
django.setup()

from app12.models import Author, Post

fake = Faker()

def add_data():
    for _ in range(100):
        author = Author.objects.create(name=fake.name())
        for _ in range(10):
            Post.objects.create(
                title=fake.sentence(),
                content=fake.text(),
                author=author
            )

if __name__ == '__main__':
    add_data()

9,访问页面

127.0.0.1:8000/app12/post_list/

相关推荐
呱呱复呱呱11 天前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
码云骑士18 天前
31-慢查询排查全流程(上)-Django-Debug-Toolbar与EXPLAIN入门
后端·python·django
龙腾AI白云18 天前
数字孪生和世界模型,二者的技术边界正在慢慢融合吗?
人工智能·django·知识图谱
码云骑士18 天前
30-在线图书管理系统-Django从零搭建到上线部署完整实战
后端·python·django
2601_9618752418 天前
花生十三资源盘|电子版|全科
python·django·flask·virtualenv·scikit-learn·pygame·tornado
码云骑士18 天前
28-Docker部署Django(下)-docker-compose编排与静态文件处理
docker·容器·django
码云骑士18 天前
23-Django-ORM的N+1问题-select_related与prefetch_related详解
后端·python·django
摸摸芋19 天前
Django框架(1)
后端·python·django
码云骑士19 天前
27-Docker部署Django(上)-从2GB到180MB的镜像瘦身实战
docker·容器·django
杰杰79819 天前
DRF的分页讲解-入门篇 三个基础分页类介绍
python·django