Home > Enterprise >  Django: Best practice to sum all total amounts based on a model field
Django: Best practice to sum all total amounts based on a model field

Time:09-23

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:

  1. id:obj1 total_price: 10
  2. id:obj3 total_price: 20
  3. id:obj2 total_price: 30
  4. id:obj1 total_price: 40
  5. id:obj2 total_price: 50

In the list I want to have these object in the list:

  1. id:obj1 total_price: 50
  2. id:obj3 total_price: 20
  3. id:obj2 total_price: 80

What is the best practice to do that?

CodePudding user response:

Model.objects.all().values("group_by_field").annotate(all_qty=Sum("total_price"))

CodePudding user response:

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:
     data.append(DataModel(
         model_id=key,
         title=var[0],
         total_price=var[1],
     ))
  • Related