Reputation: 11
I'm learning Python and Django currently... I have a database with the following fields:
ID, amount, number
I want to multiply (amount * number) for each record in database, to assign result to variables, and after that to find a sum of all variables.
For example:
Database:
I want to achieve this:
a = 100 * 14
b = 50 * 12
c = 80 * 10
d = 60 * 15
.
.
.etc
and after that, to find a SUM (a+b+c+d....etc), and to display that value in my template.
What I have done:
VIEWS:
def report(request):
prof = Test.objects.all()
response = TemplateResponse(request,'report.html', {'all': prof})
return response
MODELS:
class Test(models.Model):
number1= models.DecimalField(max_digits=5, decimal_places=2)
amount= models.IntegerField()
def __str__(self):
return self.name
@property
def profit(self):
a = self.amount * self.number1
return a
TEMPLATE
{% for games in all %}
{{ games.profit }} <br>
{% endfor %}
The code above is displaying the multiplied results for each record in database, but I do not know how to find the SUM of all those new values?
Any help will be appriciated.
Thanks
Upvotes: 1
Views: 233
Reputation: 353
Calculate the sum in views and put it into a template variable.
view:
def report(request):
all_objects = Test.objects.all()
profits = [obj.profit for obj in all_objects]
sum_profit = sum(profits)
response = TemplateResponse(request,'report.html', {'profits': prof, 'sum': sum_profit})
return response
template:
{% for each_profit in profits %}
{{ each_profit }} <br>
{% endfor %}
<p>Sum: {{sum}}</p>
Upvotes: 1