Home > Software design >  Django How to get sum of column after doing subtraction on each row?
Django How to get sum of column after doing subtraction on each row?

Time:11-10

For example, I have an item where the "soldprice" price was 10, the "paid" was 2 and the "shipcost" was 2. I am currently doing as follows:

@property
    def profit(self):
        if self.soldprice is not None and self.paid is not None and self.shipcost is not None:
            return self.soldprice - self.paid - self.shipcost

And the return should be 6, (10 - 2 - 2). I am then calling that profit property in a template.

{% for inventory in inventory %}
       <tr>
        <td><a class='btn btn-success btn-sm' href=''>View Breakdown</a>
        <td>{{inventory.id}}</td>
        <td>{{inventory.product}}</td>
        <td>{{inventory.description}}</td>
        <td>{{ inventory.profit }}</td>
       </tr>
       {% endfor %}

So I see things as below:

ID  Product    Profit
----------------------------------------
6   dessert     8.80    
7   bowls       3.37    
8   bowls       16.32   
15  chip        6.19

What is the best way to add the "Profit" column up after calling the profit property? So for example, the total for the above would be 34.68 so I can display that in the template. Any and all help is greatly appreciated.

CodePudding user response:

Because profit is not stored in the database, you can't aggragate it in your ORM query.

You can, however, quite easily loop through it in your view and add it to context for your template, assuming inventory is a recordset:

running_total = 0
for i in inventory:
    running_total  = i.profit

context['total_profit'] = running_total

Then just include it at the bottom of your table/template as {{total_profit}}

  • Related