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()