There is a model

class tt(models.Model): ... tt_like = models.IntegerField(default=0, null=True, blank=True) ... 

I bring to the template the number of all objects:

 ololo = tt.objects.all().count() 

And now I want to display the result of the sum of the tt_like field from all objects. Those. I have 7 tt model objects, each has its own tt_like field with different values, you need to summarize them.

Need to run a loop or is there a function to count? Anyway, I just can not write it right ...

    1 answer 1

    You can use the aggregate method of the queryset object:

     >>> from django.db.models Sum >>> tt.objects.aggregate(total_likes=Sum('tt_like')) {'total_likes': 0.4470664529184653} 

    Documentation on aggregation functions