How to Get Data Out of a Django Model and in to the HTML Template

Viewed 33

I have an AttendanceReport model where staff register information such as the feedback and the number of hours worked "nbr_heures"

My model:

class AttendanceReport(models.Model):
    id=models.AutoField(primary_key=True)
    consultant_id=models.ForeignKey(Consultant,on_delete=models.DO_NOTHING)
    mission_id=models.ForeignKey(Mission,on_delete=models.CASCADE,null=True)
    session_year_id=models.ForeignKey(SessionYearModel,on_delete=models.CASCADE, null=True)
    nbr_heures = models.IntegerField(blank=False)
    feedback = models.TextField(max_length=255,null=True, default="")
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now_add=True)
    objects=models.Manager()

I'm trying to the sum the values of 'nbr_heures' How can i properly do that ? I tried this but its not working..

    hours_count=AttendanceReport.objects.annotate(nbr_heur=Sum('nbr_heures'))

Thank you in advance.

1 Answers

You need to .aggregate(…) [Django-doc] here:

hours_count = AttendanceReport.objects.aggregate(
    nbr_heur=Sum('nbr_heures')
)['nbr_heur']

An .aggregate(…) will sum all records in the queryset, whereas .annotate(…) [Django-doc] will perform an aggregate per object (or per unique values if you use .values(…)).

Related