How to Use Aggregation in Django

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 rowset_table.id. (Unless explicitly overriden).

 

 

 

Also you can read more django articles

1: Django Pagination Complete Example

2: Django Sending Email to Gmail Account 

3: Build News Application in Django 

 

 

 

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

 

 

 

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.

 

 

 

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

 

 

 

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

 

 

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

 

 

 

And now open your models.py and add these models like this.

 

 

 

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

 

 

 

also you need to register these models in admin.py file.

 

 

 

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.

 

 

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

 

 

Total number of books according to publication.

 

 

 

Finding average price across all books.

 

 

 

Max price across all books.

 

 

 

Finding min price for all books.

 

 

 

Sum of prices for all books.

 

 

 

Also you can do multiple aggregation in a queryset.

 

 

 

Listing all the publisher for the book using annotate.

 

 

 

 

Also you can watch the complete video for this article

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Comments are closed.

Share via
Copy link
Powered by Social Snap
×