Difference between Django’s annotate and aggregate methods?
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Aggregate: Aggregate generate result (summary) values over an entire QuerySet. Aggregate operate over the rowset to get a single value from the rowset.(For example sum of all prices in the rowset). Aggregate is applied on entire QuerySet and it generate result (summary) values over an entire QuerySet.
In Model:
class Books(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=3)
In Shell:
Books.objects.all().aggregate(Avg(‘price’))
# Above code will give the Average of the price Column
>>> {‘price__avg’: 34.35}
Annotate: Annotate generate an independent summary for each object in a QuerySet.(We can say it iterate each object in a QuerySet and apply operation)
In Model:
class Video(models.Model):
name = models.CharField(max_length=52, verbose_name=’Name’)
user_likes = models.ManyToManyField(UserProfile, null=True, blank=True, help_text=’User can like once’, verbose_name=’Like by’)
In View:
Video.objects.values(‘id’).annotate(Count(‘user_likes’,distinct=True)
Django’s mechanism for performing a SQL
group by
is throughannotate
andaggregate
.