ORM聚合函数详解-Max和Min:
Max 和 Min :获取指定对象的最大值和最小值。
比如想要获取 Author 表中,最大的年龄和最小的年龄分别是多少。那么可以通过以下代码来实现:
from django.db.models import Max,Min result = Author.objects.aggregate(Max('age'),Min('age'))
如果最大的年龄是88,最小的年龄是18。那么以上的result将为:
{"age__max":88,"age__min":18}
比如查询卖出去的每类书的最高、最低价格:
results = Book.objects.annotate(max=Max("bookorder__price"), min=Min("bookorder__price")) for item in results: print(item.name,":", item.max, item.min) print(results.query)
具体的原生SQL如下:
SELECT `book`.`id`, `book`.`name`, `book`.`pages`, `book`.`price`, `book`.`rating`, `book`.`author_id`, `book`.`publisher_id`, MAX(`book_order`.`price`) AS `max`, MIN(`book_order`.`price`) AS `min` FROM `book` LEFT OUTER JOIN `book_order` ON (`book`.`id` = `book_order`.`book_id`) GROUP BY `book`.`id` ORDER BY NULL
具体实例截图如下: