您可以使用 aggregate() 和 annotate() 与 Avg() 一起对 Product
模型中的价格按类别进行平均,如下所示。*您需要在使用 annotate()
时使用 order_by('pk')
,否则值将按降序打印:
from django.db.models import Avg
print(
"<All products>",
Product.objects.aggregate(Avg('price'))
)
print()
for obj in Category.objects.all():
print(
obj.id, obj.name,
Product.objects.filter(category=obj)
.aggregate(Avg('price'))
)
print()
for obj in Category.objects.all():
print(
obj.id, obj.name,
obj.product_set.aggregate(Avg('price'))
)
print()
qs = Category.objects.annotate(Avg('product__price')).order_by('pk')
for obj in qs:
print(obj.id, obj.name, obj.product__price__avg)
然后,在控制台上输出以下内容:
<All products> {'price__avg': Decimal('20.1578947368421053')}
1 Fruits {'price__avg': Decimal('13.5714285714285714')}
2 Vegetable {'price__avg': Decimal('23.0000000000000000')}
3 Meat {'price__avg': Decimal('24.2500000000000000')}
4 Fish {'price__avg': Decimal('25.3333333333333333')}
1 Fruits {'price__avg': Decimal('13.5714285714285714')}
2 Vegetable {'price__avg': Decimal('23.0000000000000000')}
3 Meat {'price__avg': Decimal('24.2500000000000000')}
4 Fish {'price__avg': Decimal('25.3333333333333333')}
1 Fruits 13.5714285714285714
2 Vegetable 23.0000000000000000
3 Meat 24.2500000000000000
4 Fish 25.3333333333333333
而且,您可以将默认键price__avg
和product__price__avg
更改为priceAvg
,以便于下面所示的价格列:
from django.db.models import Avg
print(
"<All products>",
Product.objects.aggregate(priceAvg=Avg('price'))
)
print()
for obj in Category.objects.all():
print(
obj.id, obj.name,
Product.objects.filter(category=obj)
.aggregate(priceAvg=Avg('price'))
)
print()
for obj in Category.objects.all():
print(
obj.id, obj.name,
obj.product_set.aggregate(priceAvg=Avg('price'))
)
print()
qs = Category.objects.annotate(priceAvg=Avg('product__price')).order_by('pk')
for obj in qs:
print(obj.id, obj.name, obj.priceAvg)
然后,将默认密钥更改如下:
<All products> {'priceAvg': Decimal('20.1578947368421053')}
1 Fruits {'priceAvg': Decimal('13.5714285714285714')}
2 Vegetable {'priceAvg': Decimal('23.0000000000000000')}
3 Meat {'priceAvg': Decimal('24.2500000000000000')}
4 Fish {'priceAvg': Decimal('25.3333333333333333')}
1 Fruits {'priceAvg': Decimal('13.5714285714285714')}
2 Vegetable {'priceAvg': Decimal('23.0000000000000000')}
3 Meat {'priceAvg': Decimal('24.2500000000000000')}
4 Fish {'priceAvg': Decimal('25.3333333333333333')}
1 Fruits 13.5714285714285714
2 Vegetable 23.0000000000000000
3 Meat 24.2500000000000000
4 Fish 25.3333333333333333