select_related()是Django ORM(对象关系映射)中的一种查询优化方法,主要用于减少数据库查询次数,提高查询效率。当你在查询一个模型实例时,如果这个实例有ForeignKey关联到其他模型,那么select_related()可以帮助你在一次数据库查询中同时获取到这些关联模型的数据。
Test/app12
python manage.py startapp app12
Test/Test/settings.py
Test/Test/urls.py
- from django.contrib import admin
- from django.urls import path, include
-
- urlpatterns = [
- path('app12/', include('app12.urls')),
- ]
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
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})
Test/templates/12/post_list.html
- {% for post in posts %}
- <h2>{{ post.title }}h2>
- <p>By: {{ post.author.name }}p>
- <p>{{ post.content }}p>
- {% endfor %}
- from django.urls import path
- from . import views
-
- urlpatterns = [
-
- path('post_list/', views.post_list, name='post_list'),
- ]
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()
127.0.0.1:8000/app12/post_list/