In this article i want to show you How to Use Aggregation in Django , so the meaning of aggregation is “the collection of related items of content so that they can be displayed or linked to”. there are different situations that you will need to use Aggregation in Django, for example:

  • for finding “maximum”, “minimum” value of column in database table in django models.
  • for finding “count” of records in database table based on a column.
  • for finding “average” value of a group of similar objects.
  • also for finding sum of values in a column.

In most of the cases we use aggregation on columns of data type “integer”, “float”, “date”, “datetime” etc.

essentially, aggregations are nothing but a way to perform an operation on group of rows. In databases, they are represented by operators as sum, avg etc. to do these operations Django added two new methods to querysets.

these two methods are aggregate and annotate. also we can tell that in sql terms, aggregate is a operation(SUM, AVG, MIN, MAX), without a group by, while annotate is a operation with a group by on (Unless explicitly overriden).

Read Also: Django 3.0 Tutorial 2020 - Full Course for Beginners

So now first of all you need to create a new project in django using this command.

django-admin startproject MyProject

After project creation, we need to create a new App in django. make sure that you have changed your directory to the created project, in my case it is MyProject.

python startapp MyApp

So now open your _in your created App, and add your App in there. in my case it is MyApp.

    'MyApp'   #newly added 

OK after this you need to migrate your project with this command.

python migrate

Also you need to create a super user for your django project like this.

python createsuperuser

And now open your _and add these models like this.

from django.db import models

# Create your models here.

class Author(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):

class Publisher(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):

class Book(models.Model):
    name = models.CharField(max_length=300)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

    def __str__(self):

basically we have created three models. now you need to do migrations.

python makemigrations
python migrate

also you need to register these models in file.

from django.contrib import admin
from .models import Book, Author, Publisher

# Register your models here.

and after that you need to open your admin panel and add some items to your database. after that we are going to start our aggregation commands.

Now you need to open django shell, because we are using django shell for our aggregation commands.

python shell

So now you can get the number of totals books from your model like this.

In [1]: from MyApp.models import Book

In [2]: Book.objects.count()
Out[2]: 8

Total number of books according to publication.

In [5]: Book.objects.filter(publisher__name = 'Second')
Out[5]: <QuerySet [<Book: Python New Book>, <Book: Kotlin Book>]> 	

Finding average price across all books.

In [6]: from django.db.models import Avg

In [7]: Book.objects.all().aggregate(Avg('price'))
Out[7]: {'price__avg': Decimal('121.25')}

Max price across all books.

In [8]: from django.db.models import Max

In [9]: Book.objects.all().aggregate(Max('price'))
Out[9]: {'price__max': Decimal('185')}

Finding min price for all books.

In [10]: from django.db.models import Min

In [11]: Book.objects.all().aggregate(Min('price'))
Out[11]: {'price__min': Decimal('50')}

Sum of prices for all books.

In [12]: from django.db.models import Sum

In [13]: Book.objects.all().aggregate(Min('price'))
Out[13]: {'price__min': Decimal('50')}

Also you can do multiple aggregation in a queryset.

In [5]: Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': Decimal('121.25'),
 'price__max': Decimal('185'),
 'price__min': Decimal('50')}

Listing all the publisher for the book using annotate.

In [9]: from MyApp.models import Publisher

In [10]: from django.db.models import Count

In [11]: pubs = Publisher.objects.annotate(num_books=Count('book'))

In [12]: pubs[0].num_books
Out[12]: 3

#django #python #webdev

How to Use Aggregation in Django
12.45 GEEK