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/

相关推荐
luoluoal2 小时前
基于python的语音识别与蓝牙通信的温控系统(源码+文档)
python·mysql·django·毕业设计·源码
linuxxx1105 小时前
request.build_absolute_uri()关于使用IP+端口
网络·python·网络协议·tcp/ip·django
linuxxx1105 小时前
request.build_absolute_uri()用法
python·django
linuxxx1109 小时前
request.build_absolute_uri()为什么没有获得端口?
python·nginx·django
㳺三才人子10 小时前
初探 Python + Django
开发语言·python·django
java1234_小锋1 天前
[免费]基于Python的Django+Vue3在线商城系统(简易版)【论文+源码+SQL脚本】
python·django·商城系统·python毕业设计·在线商城
qq_13948428821 天前
python基于大数据技术的酒店消费数据分析系统
大数据·python·scrapy·django·flask
wa的一声哭了1 天前
内积空间 内积空间二
java·开发语言·python·spring·java-ee·django·maven
二等饼干~za8986681 天前
GEO优化---关键词搜索排名源码开发思路分享
大数据·前端·网络·数据库·django
luoluoal2 天前
基于python的小区监控图像拼接系统(源码+文档)
python·mysql·django·毕业设计·源码