Reputation: 161
Here is my code
reports: queryset
for reports in reports:
data.append(DataModel(
model_id=report.num,
title=report.title,
total_price=report.total_amount,
))
This code will create some DataModel objects and will append the object into a list.
I want to sum total_price
of all the objects with the same obj.id
.
For example: If we have these objects on the queryset:
In the list I want to have these object in the list:
What is the best practice to do that?
Upvotes: 0
Views: 107
Reputation: 5257
It's not immediately obvious how you can do it without looping through twice. The assumption here is that reports with the same model id will share the same title, otherwise you may need to concatenate them when you add the total_amounts.
reports: queryset
totals_dict = {}
for report in reports:
#loop through to check for multiple amounts, storing results in dict
#using report_num as key
if report.num in totals_dict:
totals_dict[report.num][1] += report.total_amount
else:
totals_dict.setdefault(report.num, []).append(report.title)
totals_dict[report.num].append(report.total_amount)
#create data list using dict
for key, var in totals_dict.items():
data.append(DataModel(
model_id=key,
title=var[0],
total_price=var[1],
))
Upvotes: 0
Reputation: 933
Model.objects.all().values("group_by_field").annotate(all_qty=Sum("total_price"))
Upvotes: 2