select_related()的作用
select_related()是Django ORM(对象关系映射)中的一种查询优化方法,主要用于减少数据库查询次数,提高查询效率。当你在查询一个模型实例时,如果这个实例有ForeignKey关联到其他模型,那么select_related()可以帮助你在一次数据库查询中同时获取到这些关联模型的数据。
1,创建应用
Test/app12
python manage.py startapp app12
![](https://i-blog.csdnimg.cn/direct/9c4310510b5f41fabaaf440a26ce697e.png)
2,注册应用
Test/Test/settings.py
![](https://i-blog.csdnimg.cn/direct/88fbec52ea0145d58c463f2a4404929b.png)
3,添加应用路由
Test/Test/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('app12/', include('app12.urls')),
]
![](https://i-blog.csdnimg.cn/direct/18f75b5c84a94e178b38417116f2f198.png)
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
![](https://i-blog.csdnimg.cn/direct/780a4dd137a84fcf96ccb1289ab793bb.png)
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})
![](https://i-blog.csdnimg.cn/direct/aa9709be263640e89a5a08abcddce54a.png)
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 %}
![](https://i-blog.csdnimg.cn/direct/e5a3e8f0188c49c2b8d765814e346e35.png)
7,添加路由地址
from django.urls import path
from . import views
urlpatterns = [
path('post_list/', views.post_list, name='post_list'),
]
![](https://i-blog.csdnimg.cn/direct/b86402bce477498ab3c4422b96e59791.png)
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()
![](https://i-blog.csdnimg.cn/direct/95c63efacefa48e18eacfc8d939a1805.png)
![](https://i-blog.csdnimg.cn/direct/fda91f1f775b44be8f03e72191aaa835.png)
9,访问页面
127.0.0.1:8000/app12/post_list/
![](https://i-blog.csdnimg.cn/direct/46706c5a558441aa8ca1a27215ad0051.png)
![](https://i-blog.csdnimg.cn/direct/55558db76ff74c9c895a0d68825ab22e.png)