from django.http import HttpResponse from .models import Author from django.db.models import Max, Min from django.db import connection def index(request): # Max和Min result = Author.objects.aggregate(max_age=Max('age'),min_age=Min('age')) print(result) return HttpResponse("success !")
{'max_age': 57, 'min_age': 34}python
print(connection.queries)
[{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'}, {'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'}, {'sql': 'SELECT MAX(`author`.`age`) AS `max_age`, MIN(`author`.`age`) AS `min_age` FROM `author`', 'time': '0.000'}]
from django.http import HttpResponse from .models import Author,Publisher,Book,BookOrder from django.db.models import Avg,Count,Sum, Max, Min from django.db import connection def index(request): # 獲取每一種圖書預約價格的最高值和最低值 books = Book.objects.annotate(max_price=Max('bookorder__price'), min_price=Min('bookorder__price')) for book in books: print("%s,最高價格:%s,最低價格:%s" % (book.name,book.max_price, book.min_price)) # 打印出結果: # 三國演義,最高價格:104.0,最低價格:99.0 # 水滸傳,最高價格:115.0,最低價格:100.0 # 紅樓夢,最高價格:105.0,最低價格:99.0 # 西遊記,最高價格:None,最低價格:None return HttpResponse("success !")