defer (), only (): These two methods will return a "QuerySet" object and the "QuerySet" is loaded with the model, unlike the values () and values_list () is a dictionary or tuples.
1. defer: This method is used to tell the "ORM", a model in the query when filtering out a field note: Use the "defer" in the field, if after using this field, will re-initiate a request, so be careful.
Sample code is as follows:
def index6(request):
books = Book.objects.defer('name')
for book in books:
print("%s, %s" % (book.id, book.author))
print(connection.queries)
return HttpResponse("success")
django underlying sql statement would be:
[{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'},
{'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'},
# 由下面的这条sql语句可以看出,在执行sql语句查找book的相关属性的时候,没有查找我们传递进defer()的属性字段name
{'sql': 'SELECT `book`.`id`, `book`.`pages`, `book`.`price`, `book`.`rating`, `book`.`author_id`, `book`.`publisher_id`, `book`.`score` FROM `book`', 'time': '0.000'},
{'sql': 'SELECT `author`.`id`, `author`.`name`, `author`.`age`, `author`.`email` FROM `author` WHERE `author`.`id` = 5 LIMIT 21', 'time': '0.000'},
{'sql': 'SELECT `author`.`id`, `author`.`name`, `author`.`age`, `author`.`email` FROM `author` WHERE `author`.`id` = 1 LIMIT 21', 'time': '0.000'},
{'sql': 'SELECT `author`.`id`, `author`.`name`, `author`.`age`, `author`.`email` FROM `author` WHERE `author`.`id` = 4 LIMIT 21', 'time': '0.000'},
{'sql': 'SELECT `author`.`id`, `author`.`name`, `author`.`age`, `author`.`email` FROM `author` WHERE `author`.`id` = 3 LIMIT 21', 'time': '0.000'}]
2. only: This method is used to tell the "ORM", a model in a query, you can just extract a field. Note: There is no increase in "only" in the field are filtered out, and later use, it would re-initiate a request again, so this operation to be cautious.
Sample code is as follows:
def index7(request):
books = Book.objects.only('name')
for book in books:
print(book.name)
print(connection.queries)
return HttpResponse("Success")
django underlying sql statement would be:
[{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'},
{'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'},
# 由下面这条查询语句可以看出,虽然只打印了book.name,但是在执行查询的语句的时候依旧查询了book.id, 并且在执行查询book.id之前并没有再次向数据库发起一次查询操作
# 由此可以看出,数据库表中的id字段是不能进行操作的
{'sql': 'SELECT `book`.`id`, `book`.`name` FROM `book`', 'time': '0.000'}]