[ad_1]
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)
pages = models.IntegerField()
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")
video = models.FileField(upload_to=document_path, verbose_name="Upload
video")
created_by = models.ForeignKey(User, verbose_name="Created by",
related_name="create_%(class)s")
user_likes = models.ManyToManyField(UserProfile, null=True,
blank=True, help_text="User can like once",
verbose_name="Like by")
In View:
videos = Video.objects.values('id', 'name','video').annotate(Count('user_likes',distinct=True)
In view it will count the likes for each video
[ad_2]