Retrieve average, minimum, maximum values from model field using Django Aggregation

Reading Time : ~ .

Django queries help to create, retrieve, update and delete objects. But sometimes we need to get summered values from the objects. Then a Simple solution is to use Django aggregate feature Here are simple examples of how to use aggregation.

app/models.py

class company(models.Model):

    name=models.CharField(max_length=20)

    est=models.IntegerField(max_length=4)

class feature(models.Model):

    name=models.CharField(max_length=20)

class device(models.Model):

    name=models.CharField(max_length=20)

    Code=models.IntegerField()

    Company=models.ForeignKey(company)

    features=models.ManyToManyField(feature)

To perform Min Max and Avg on specific column

 

>>> from django.db.models import Avg, Max, Min, Sum
>>> device.objects.all().aggregate(Avg('price'))
    {'price__avg': 12234.0}
>>> device.objects.all().aggregate(Max('price'))
    {'price__max':587961 }
>>> device.objects.all().aggregate(Min('price'))
{'price__min': 01245}

To know the children count of a foreign key field. 

>>> Comp_Devices=company.objects.annotate(no_of_devices=Count('device'))
>>> Comp_Devices[0].no_of_devices
36
>>> Comp_Devices[0].name
u'Micro'
>>> Comp_Devices[1].no_of_devices
1

the same procedure can be followed for ManyToMany field Columns

>>> Dev_features_count = device.objects.annotate(num=Count('features'))

>>> Dev_features_count[0].num

3

>>> Dev_features_count[1].num

2

>>> 

 

You can perform some complex queries like

To know the devices which have more than two features

>>> Dev_features= device.objects.annotate(num=Count('features')).filter(num__gt=2)

>>> Dev_features[0].num

3

>>> 
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Sendgrid Inbound Email Parsing with django Nikhila Mergu

Using the Inbound parse webhook, we can parse the contents, attachments of an incoming email.

Inbound Parse API follows 3 steps:
1. sending an ...

Continue Reading...
Dynamically Adding Google Maps with Marker In Django Nikhila Mergu

Google Maps allows you to display maps on your web site, we can also customize maps, and the information on maps.
The Google Maps API ...

Continue Reading...
Integration Of GitHub API with python django Nikhila Mergu

Using Github integration, we can get the user verified email id, general information, git hub URL, id, disk usage, public, private repo's, gists and followers, ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties