惰性机制:Publisher.objects.all()或者.filter()等都只是返回了一个QuerySet(查询结果集对象),它并不会马上执行sql,而是当调用QuerySet的时候才执行sql,为了测试,我们加上 sql 日志。
在 settings.py 文件上修改
1 # 在最后添加 2 LOGGING = { 3 ‘version‘: 1, 4 ‘disable_existing_loggers‘: False, 5 ‘handlers‘: { 6 ‘console‘:{ 7 ‘level‘:‘DEBUG‘, 8 ‘class‘:‘logging.StreamHandler‘, 9 }, 10 }, 11 ‘loggers‘: { 12 ‘django.db.backends‘: { 13 ‘handlers‘: [‘console‘], 14 ‘propagate‘: True, 15 ‘level‘:‘DEBUG‘, 16 }, 17 } 18 }
在 views.py 上修改
1 from django.shortcuts import render, HttpResponse 2 from app01 import models 3 from app01.models import Book,Author,Publisher 4 5 # Create your views here. 6 7 def data_oper(req): 8 9 obj_set = models.Book.objects.filter(id=2) 10 11 return HttpResponse("Hello world")
浏览器访问 http://127.0.0.1:8000/data_oper/ 结果显示 sql 语句没有执行
调用 QuerySet ,在 views.py 上修改
1 rom django.shortcuts import render, HttpResponse 2 from app01 import models 3 from app01.models import Book,Author,Publisher 4 5 # Create your views here. 6 7 def data_oper(req): 8 9 obj_set = models.Book.objects.filter(id=2) 10 for obj in obj_set: 11 print(obj.title) 12 13 return HttpResponse("Hello world")
浏览器访问 http://127.0.0.1:8000/data_oper/ 结果显示 sql 语句已执行
原文地址:https://www.cnblogs.com/zyq6/p/11805905.html
时间: 2024-11-03 15:35:00