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/

相关推荐
QD.Joker2 小时前
Django ORM 单表操作
数据库·django
gongzairen14 小时前
Ngrok 内网穿透实现Django+Vue部署
后端·python·django
快乐点吧1 天前
【代理错误 django】Request error: HTTPSConnectionPool(host=‘‘, port=443): 、
后端·python·django
KENYCHEN奉孝1 天前
一个基于Django的写字楼管理系统实现方案
数据库·python·django·sqlite
程序媛徐师姐2 天前
Python Django基于协同过滤算法的招聘信息推荐系统【附源码、文档说明】
python·django·协同过滤算法·招聘信息推荐系统·招聘信息·python招聘信息推荐系统·python招聘信息
橘猫云计算机设计2 天前
基于django云平台的求职智能分析系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·spring boot·后端·python·django·毕业设计
声声codeGrandMaster2 天前
Django之modelform使用
后端·python·django
松前卡气加超级漂3 天前
Django:高效构建现代Web应用的利器
前端·python·django
alicema11113 天前
Python-Django集成yolov识别模型摄像头人数监控网页前后端分离
开发语言·后端·python·算法·机器人·django
杨涣群3 天前
Django 开发服务器
python·django