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底層執行的sql語句爲:python
[{'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'}]
def index7(request): books = Book.objects.only('name') for book in books: print(book.name) print(connection.queries) return HttpResponse("Success")
django底層執行的sql語句爲:sql
[{'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'}]