安装django-debug-tools
性能测试:
settings.py
INSTALLED_APPS = [
...
'app01', # 注册app
]
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号
TEMPLATES = [
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
]
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from app01 import views
from django.conf.urls import include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
url('index/', views.index)
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
views.py
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
def index(request):
v = models.U.objects.all().prefetch_related('userType')
return render(request, 'index.html', {"v": v})
templates/index.html
{% for item in v %}
{{ item.name }} {{ item.email }} {{ item.userType.caption }}
{% endfor %}
初始化数据库
python manage.py makemigrations
python manage.py migrate
页面显示;
models.U.objects.all():
models.U.objects.all().select_related(‘userType’):
models.U.objects.all().prefetch_related('userType')
性能对比:
select_related > prefetch_related > all()