1

What is advantage and disadvantage of using aggregate and annonate method? I already read the documentation on how to use the aggregate and annonate method, but i still dont know the difference between them, I need to know when to use the annonate and aggregate , please tell me,

I know I'm not the only one confused about it when to use annonate and aggregate method. especially when you are a beginner in django, thanks

  • 1
    Does this answer your question? [Difference between Django's annotate and aggregate methods?](https://stackoverflow.com/questions/7981837/difference-between-djangos-annotate-and-aggregate-methods) – ChidG Mar 03 '20 at 08:05
  • no, because i need to know when the to use the annotate and aggregate –  Mar 03 '20 at 08:08

1 Answers1

0

You can add extra fields that contain some processes to your queryset for each item with annotate.With aggregate, you can get a result for all queryset items. For example you have a model like that:

 class MyModel(models.Model):
     field_first = models.IntegerField() 
     field_second = models.IntegerField() 

Example for annotate: If you want to add a sum field for each records, you can use annotate:

items = MyModel.objects.annotate(summary=F('field_first') + F('field_second'))
for item in items:
    print(item.summary) # you have a summary field for items after this

Example for aggregate: If you want to get sum of field_first for all records, you can use aggregate

total =  MyModel.objects.aggregate(sum_first=Sum('field_first')) # it returns as a dict
print(total) # {'sum_first': total value} 
kamilyrb
  • 2,502
  • 3
  • 10
  • 25
  • ahh i see, so if i want to compute the average, I will use the aggregate, i want to have a computation of some field i will use the annotate right? –  Mar 03 '20 at 08:44
  • This answer help me to fully understand , When to use the annotate and aggregate , thanks for this –  Mar 03 '20 at 09:12