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, there is a need to get a summary of all these items. 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. Whereas in the case of aggregate, the summary is calculated for the entire queryset. So when the whole query set is expected to be considered, Django annotate must be used.
Syntax:
Annotated_output = Model.Objects.annotate(variable=aggregate_function(columnname))
The syntax explains identifying the annotated value. First, the Model in which the system database is targeted for aggregation or annotation is declared, then the objects associated with the Model. After this, the annotate method is used to set the annotate process; the variable involved is declared within the annotate method. The aggregate function expected to be performed is mentioned next. Next, the aggregate function will be performed on the column name mentioned within the average function used. 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 allows the aggregate method to be encapsulated within it. The column that will be considered for annotation has to be declared within the aggregate function.
- The column value will be expected to be enclosed within a pair of single quotations. In addition, the output of the annotate will be assigned to the annotated output variable, which can be flexibly used for identifying the output of the annotation.
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. A detailed example with the corresponding code changes is also submitted to explain the real-time execution of annotate method.