add values inside for loop

{% for transid in testing_list %}
{{ transid.transid }} {{ transid.transdate }} {{ transid.transdetails }} {{ transid.transmode}} {{ transid.transamount}}
{% endfor %}

Above is my “testing.html” code.

I want to sum “transamount” and give a Total Balance.
Also I want to sum it based “transmode” and give a mode vise balance.

Please guide me, I am very much new.

You do not do that in your template. That’s something to be done in the view and passed to the template to be rendered.

Thanks for the reply.
below is my views.py

def testing(request):
testing_list = Daily.objects.all()
return render(request, ‘testing.html’, {‘testing_list’: testing_list})

where / how should I add those values to get grand total and “mode” vise total.

You’ve got two different options:

  • You can use annotations and aggregations to perform those calculations within the database layer.

  • You can process your queryset in your view.

In either case, you then add the results of your calculations to the context being passed to the template in the render function to be rendered on that page.

Thanks.

I will search how to do the options which you have mentioned, and will come back if I find.

Also, when posting code here, enclose the code between lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted.

For example, your view would look like this (with comments added by me):

# The line above this is ```
def testing(request):
    testing_list = Daily.objects.all()
    return render(request, ‘testing.html’, {‘testing_list’: testing_list})
# The line after this is ```
def testing(request):
      return render(request, 'my.html')

Thanks for educating.

def testing(request):
	testing_list = Daily.objects.all()
	balance = 0
	for b in Daily.objects.all():
		balance = balance + b.transamount 

	print(balance)
	return render(request, 'testing.html', {'testing_list': testing_list})

I am getting the value “balance” in the command window, need to find how to pass that value to ‘testing’html’

You add that as another value to the context that you’re passing to the template in the call to render.

Yeah! I got it.
I am just searching to find out, how to render multiple values.

def testing(request):
	testing_list = Daily.objects.all()
	balance = 0
	cashbal = 0
	enbdbal = 0
	nolbal = 0
	payitbal = 0
	sibbal = 0

	for b in Daily.objects.all():
		balance = balance + b.transamount
		if b.transmode_id == 1:
			cashbal = cashbal + b.transamount
		elif b.transmode_id == 2:
			enbdbal = enbdbal + b.transamount
		elif b.transmode_id == 3:
			nolbal = nolbal + b.transamount
		elif b.transmode_id == 4:
			payitbal = payitbal + b.transamount
		else:
			sibbal = sibbal + b.transamount



	print(balance, cashbal, enbdbal, nolbal, payitbal, sibbal)
	return render(request, 'testing.html', {'testing_list': testing_list, 'balance': balance, 'cashbal': cashbal, 'enbdbal': enbdbal, 'nolbal': nolbal, 'payitbal': payitbal, 'sibbal': sibbal})

wow! I learned it now. still need to go, thanks.

Will be approaching again for other doubts.

Looks so messy.

Please guide me if I can reduce / compact the coding

Do you have any control over what that Daily model looks like? Or are you dealing with an external feed giving you no control over the contents?
(What does the Daily model look like?)

from django.db import models

# Create your models here.
class MasterCategory(models.Model):
	masterid = models.AutoField(primary_key=True)
	name = models.CharField(max_length=25, null=False)

	def __str__(self):
		return "%s %s" %(self.name, self.masterid)

class PaymentMode(models.Model):
	modeid = models.AutoField(primary_key=True)
	name = models.CharField(max_length=10, null=False)

	def __str__(self):
		return "%s %s" %(self.name, self.modeid)

class Daily(models.Model):
	transid = models.AutoField(primary_key=True)
	transdate = models.DateField()
	transdetails = models.CharField(max_length=25)
	transcategory = models.ForeignKey(MasterCategory, on_delete=models.CASCADE)
	transmode = models.ForeignKey(PaymentMode, on_delete=models.CASCADE)
	transsubdetails = models.CharField(max_length=100, null=True)
	transamount = models.FloatField()	

	def __str__(self):
		return "%s %s %s %s %s %s %s" %(self.transid, self.transdate, self.transdetails, self.transcategory, self.transmode, self.transsubdetails, self.transamount)

Above is model.py

First, you absolutely do not want to set up your code doing comparisons to the id field of a model. Your transmode field is an FK to PaymentMode, where the “meaning” of that relationship is the name field of that model.

What are the corresponding names for these transmode values?

Also:

I am very much new, and I don’t know how to organize my database.
transmode table has constant values “Cash, enbd, nol, payit, sib”, I was wondering if I can do it in another way rather than “model”.
In my scenario transmode_id a field is created in “Daily” table, so that I am checking if “transmode_id” is 1-5.

Ok, I understand this so far. What I’m trying to understand is where this data for the Daily model is coming from. Do you have any control over that, or is that data coming to you from an external source where the format is fixed by that source?

And that’s what’s wrong. You don’t compare transmode_id for any reason at all.

I am adding the values now directly from admin site.
Previous values all imported from “csv” file.

comparing transmode_id is bringing correct result, or shall I compare directly with transmode == “Cash” like this ?

** there is no transmode column in my “Daily” Table, only “transmode_id” is available

from django.contrib import admin
from .models import MasterCategory, PaymentMode, Daily

# Register your models here.

admin.site.register(MasterCategory)
admin.site.register(PaymentMode)
admin.site.register(Daily)

above is my admin.py

You’re still not answering the question I’m asking.

Do you control the format of the Data model, or is that format forced upon you because you’re working with data you have no control over?

You would compare transmode.name == “Cash” - or whatever the name attribute would be in the related model.

I am able to do the comparison by name now.

if b.transmode.name == "Cash": 

this way it’s working fine.