django queryset get avg min and max price of all products

+1 vote
88 views
asked Mar 14 by anonymous

I know how to get avg, min and max value based on column via sql queries, i am wondering if using django ORM i can get all three average, max and minimum price using one query.

My django model look like this.

class Product(models.Model):
    name = models.CharField(max_length=300)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    ...
    ...

1 Answer

+1 vote
answered Mar 14 by anonymous
 
Best answer

Yes you can perform more than one aggeregate in django orm, aggregate() can handle more than one argument.

from django.db.models import Avg, Max, Min
Product.objects.aggregate(Avg('price'), Max('price'), Min('price'))

Output

{'price__avg': 90.35, 'price__max': Decimal('290.20'), 'price__min': Decimal('12.99')}
...