Back to writing

Article

Aggregation in Django

Django’s aggregate() method calculates a summary value across a queryset. In this example, Sum totals the hours worked by one teammate for each report, and the result is added to a response list.

response_work_projects = []

for report in report_statics:
workperteammates = report.workperteammate_set.filter(mate__id=user_id)
total_hours_worked = workperteammates.aggregate(sum_hours_worked=Sum('hours_worked'))['sum_hours_worked']
report_data = {
'title': report.title,
'hour': total_hours_worked
}
response_work_projects.append(report_data)