Updated May 23, 2023
Introduction to Django Annotate
There is always a need to get an aggregated value of an item. For example, when a group of records exists or when a query set has been defined, obtaining a summary of all these items becomes necessary. In the Django framework, annotate and aggregate are responsible for identifying a given value set summary. Among these, annotate identifies the summary from each item in the queryset. In the case of aggregation, the summary is calculated for the entire queryset. Therefore, when you want to consider the entire query set, you should use Django’s annotate.
Syntax:
Annotated_output = Model.Objects.annotate(variable=aggregate_function(columnname))
The syntax explains identifying the annotated value. First, the system declares the Model, which targets the system database for aggregation or annotation, and then declares the objects associated with the Model. After this, the annotate method sets the annotate process; The annotate method declares the involved variable. It mentions the expected aggregate function to be performed. Then, the aggregate function will perform on the column name mentioned within the average function. Finally, the annotated output variable will replace the entire aggregate output.
How Annotate Works?
- The process in which annotation works is straightforward and lean; it expects the Model for which the annotation is performed and the aggregate function through which the annotation will be wrapped upon.
- The annotate function encapsulates the aggregate method within it. You need to declare the column that will be considered for annotation within the aggregate function.
- You must enclose the column value within a pair of single quotations. Additionally, the annotate function will assign the output to the annotated output variable, allowing flexible identification of the annotation output.
Example of Django Annotate
Given below is the example of Django Annotate:
a. Changes in the Models.py file
Code:
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Object(models.Model):
Django_Annotate_redirect__Example_name = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_thegai = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_State = models.CharField(max_length=50,null=True)
Django_Annotate_redirect__Example_District = models.CharField(max_length=50,null=True)
Django_Annotate_redirect__Example_Address = models.TextField(null=True)
Django_Annotate_redirect__Example_Phone = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_profession = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_salary = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Rasi = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Phone = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_profession = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_salary = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Rasi = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Phone = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_profession = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_salary = models.BigInteger_Example_Field(null=True)
Django_Annotate_redirect__Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Rasi = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Nakshatra = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Django_Annotate_redirect__Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Django_Annotate_redirect__Example_Rasi = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
b. Create a view for the form
Code:
def Main_page(request):
Post_keys = []
Object_id_str_list = []
Objects = Object.objects.all()
# Object_Image = Objects.Image
# context2['Image'] = Object_Image
context = {'Objects':Objects}
if request.method == 'GET':
State = request.GET.get('state', '')
District = request.GET.get('district', '')
thegai = request.GET.get('thegai', '')
Rasi = request.GET.get('Rasi', '')
print(len(State),len(District),District, Rasi)
if len(State) > 0:
Filter_context = {}
Object = Object.objects.filter(State=str(State))
Filter_context = {'Objects':Object}
return render(request,'Mainpage.html',Filter_context)
if len(District) > 0:
Filter_context = {}
Object = Object.objects.filter(District=str(District))
print(Object)
Filter_context = {'Objects':Object}
return render(request,'Mainpage.html',Filter_context)
if len(thegai) > 0:
Filter_context = {}
Object = Object.objects.filter(thegai=str(thegai))
print(Object)
Filter_context = {'Objects':Object}
return render(request,'Mainpage.html',Filter_context)
if len(Rasi) > 0:
Filter_context = {}
Object = Object.objects.filter(Rasi=str(Rasi))
print(Object)
Filter_context = {'Objects':Object}
return render(request,'Mainpage.html',Filter_context)
if len(Rasi) > 0:
Filter_context = {}
Object = Object.objects.filter(Rasi=str(Rasi))
print(Object)
Filter_context = {'Objects':Object}
return render(request,'Mainpage.html',Filter_context)
Count_salary_annotate_Count = Bride.objects.annotate(total_profile=Count('salary'))
Count_salary_aggregate_Count = Bride.objects.aggregate(total_profile=Count('salary'))
Count_salary_annotate_Max = Bride.objects.annotate(total_profile=Max('salary'))
Count_salary_aggregate_Max = Bride.objects.aggregate(total_profile=Max('salary'))
Count_salary_annotate_Count = Bride.objects.annotate(total_profile=Count('salary'))
Count_salary_aggregate_Count = Bride.objects.aggregate(total_profile=Count('salary'))
Count_salary_annotate_Max = Bride.objects.annotate(total_profile=Max('salary'))
Count_salary_aggregate_Max = Bride.objects.aggregate(total_profile=Max('salary'))
Count_salary_annotate_Min = Bride.objects.annotate(total_profile=Min('salary'))
Count_salary_aggregate_Min = Bride.objects.aggregate(total_profile=Min('salary'))
Count_salary_annotate_Avg = Bride.objects.annotate(total_profile=Avg('salary'))
Count_salary_aggregate_Avg = Bride.objects.aggregate(total_profile=Avg('salary'))
print("Annotate Output by Count:",Count_salary_annotate_Count[0].total_profile)
print("Aggregate Output by Count: ",Count_salary_aggregate_Count)
print("Annotate Output by Max:",Count_salary_annotate_Max[0].total_profile)
print("Aggregate Output by Max: ",Count_salary_aggregate_Max)
print("Annotate Output by Min:",Count_salary_annotate_Min[0].total_profile)
print("Aggregate Output by Min: ",Count_salary_aggregate_Min)
print("Annotate Output by Avg:",Count_salary_annotate_Avg[0].total_profile)
print("Aggregate Output by Avg: ",Count_salary_aggregate_Avg)
return render(request,'Mainpage.html',context)
@login_required
def profile_reg_user(request):
Filter_context = {}
current_user = request.user
bride = Bride.objects.filter(Creator=current_user)
Count_salary_annotate_Count = Bride.objects.annotate(total_profile=Count('salary'))
Count_salary_aggregate_Count = Bride.objects.aggregate(total_profile=Count('salary'))
Count_salary_annotate_Max = Bride.objects.annotate(total_profile=Max('salary'))
Count_salary_aggregate_Max = Bride.objects.aggregate(total_profile=Max('salary'))
Count_salary_annotate_Min = Bride.objects.annotate(total_profile=Min('salary'))
Count_salary_aggregate_Min = Bride.objects.aggregate(total_profile=Min('salary'))
Count_salary_annotate_Avg = Bride.objects.annotate(total_profile=Avg('salary'))
Count_salary_aggregate_Avg = Bride.objects.aggregate(total_profile=Avg('salary'))
print("Annotate Output by Count:",Count_salary_annotate_Count[0].total_profile)
print("Aggregate Output by Count: ",Count_salary_aggregate_Count)
print("Annotate Output by Max:",Count_salary_annotate_Max[0].total_profile)
print("Aggregate Output by Max: ",Count_salary_aggregate_Max)
print("Annotate Output by Min:",Count_salary_annotate_Min[0].total_profile)
print("Aggregate Output by Min: ",Count_salary_aggregate_Min)
print("Annotate Output by Avg:",Count_salary_annotate_Avg[0].total_profile)
print("Aggregate Output by Avg: ",Count_salary_aggregate_Avg)
Filter_context = {'brides':bride}
return render(request,'Profiles_reg_user.html',Filter_context)
@login_required
def form_update(request,pk):
update_profile = Bride.objects.get(id=pk)
form = Valueform(instance=update_profile)
context = {'form':form}
if request.method == 'POST':
form = Valueform(request.POST,instance=update_profile,files=request.FILES)
print(form)
if form.is_valid():
post = form.save()
post.Creator = request.user
print('Creator user stored',request.user)
post.save()
obj = form.instance
return render(request,'form.html', {"obj": obj,"form": form})
return render(request,'form.html', {"form": form})
def Json_Response(request):
jsondata = [ {'index_1': 'data_1'},
{'index_2': 'data_2'},
{'index_n': 'data_n'},
]
return JsonResponse(jsondata, safe=False)
c. html.py
Code:
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>Home</title>
{% load static %}
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home! </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
</div>
</nav>
<div class="tablediv">
<table class="table" >
{% for bride in brides %}
<tr align="center">
<td>{{bride.name}} </td>
<td>{{bride.age}}</td>
<td>
<form method="POST">
{% csrf_token %}
<a class="btn btn-sm btn-info" href="{% url 'update' bride.id %}" name="{{bride.id}}">Update profile</a>
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
function redirect3() {
window.location.href = "http://127.0.0.1:8000/login";
}
function redirect4() {
window.location.href = "http://127.0.0.1:8000/signup";
}
function redirect5() {
window.location.href = "http://127.0.0.1:8000/";
}
function redirect6() {
window.location.href = "http://127.0.0.1:8000/logout";
}
/* Open when someone clicks on the span element */
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
/* Close when someone clicks on the "x" symbol inside the overlay */
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
</body>
</html>
Output:
Conclusion
The article above shows the annotate method; it describes the syntax behind formulating an annotate method and mentions the process through which it usually works. The code executes the annotate method in real-time and submits a detailed example with the corresponding code changes.
Recommended Articles
We hope that this EDUCBA information on “Django Annotate” was beneficial to you. You can view EDUCBA’s recommended articles for more information.