For example, to find the price range of books offered in each store,you could use the annotation:
以下语句查的是每一个商店中书的最高价和最低价,注意是每一个商店,结果是按商店分的数组
相当于给每条数据做注释。
>>> from django.db.models import Max, Min
>>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
This tells Django to retrieve the Store
model, join (through themany-to-many relationship) with the Book
model, and aggregate on theprice field of the book model to produce a minimum and maximum value.
The same rules apply to the aggregate()
clause. If you wanted toknow the lowest and highest price of any book that is available for salein any of the stores, you could use the aggregate:
以下语句查的是所有商店中,书的最高价和最低价,注意是所有商店,或者说任意一个商店,结果是一个最大值和一个最小值。
这里是对全部数据求最大最小值,是单纯的数据聚合功能。
>>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))
https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#joins-and-aggregates