惰性机制:Publisher.objects.all()或者.filter()等都只是返回了一个QuerySet(查询结果集对象),它并不会马上执行sql,而是当调用QuerySet的时候才执行sql,为了测试,我们加上 sql 日志。
在 settings.py 文件上修改
# 在最后添加
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'Django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
在 views.py 上修改
from djanGo.shortcuts import render, HttpResponse
from app01 import models
from app01.models import Book,Author,Publisher
# Create your views here.
def data_oper(req):
obj_set = models.Book.objects.filter(id=2)
return HttpResponse("Hello world")
浏览器访问 http://127.0.0.1:8000/data_oper/ 结果显示 sql 语句没有执行
调用 QuerySet ,在 views.py 上修改
rom django.shortcuts import render, HttpResponse
from app01 import models
from app01.models import Book,Author,Publisher
# Create your views here.
def data_oper(req):
obj_set = models.Book.objects.filter(id=2)
for obj in obj_set:
print(obj.title)
return HttpResponse("Hello world")
浏览器访问 http://127.0.0.1:8000/data_oper/ 结果显示 sql 语句已执行