Reputation: 349
I'm having trouble understanding how to relate additional information to an existing Django list and if I should be doing this in my templates or in the view somehow. Please see the below scenario:
class Team(models.Model):
team_name = models.CharField(max_length=200)
For example in my view I am retrieving a list of all sports games and returning them:
def get_teams(request):
teams = Team.objects.all()
context = RequestContext(request, {
'teams': teams,
})
return context
I would like to add some stats to the teams which I can then access in my template in the below fashion:
def get_teams(request):
teams = Team.objects.all()
for team in teams:
team_win_percent(team)
team_lose_percent(team)
context = RequestContext(request, {
'teams': teams,
})
return context
def team_win_percent(team)
team_win_rate = [calculations here]
return team_win_rate
def team_lose_percent(team)
team_lose_rate = [calculations here]
return team_lose_rate
What I am struggling to understand is how to add team_win_percentage and team_lose_percentage to my teams list so I can reference them in my template?
Any guidance much appreciated!
Upvotes: 0
Views: 183
Reputation: 54
You could also for a few number of records append some field to the model query result the will be accessible from the template
class Team(models.Model):
team_name = models.CharField(max_length=200)
def get_teams(request):
teams = Team.objects.all()
for team in teams:
team.team_win_percent = calculate_team_win(team)
team.team_lose_percent = calculate_team_loss(team)
....
In template
{% for team in teams %}
team win percentage = {{ team.team_win_percent }}
team lose percentage = {{ team.team_lose_percent }}
{% endfor %}
Upvotes: 1
Reputation: 6009
You have to write this as as a model method;
class Team(models.Model):
team_name = models.CharField(max_length=200)
def team_win_percent(self):
#self = team object
team_win_rate = [calculations here]
return team_win_rate
def team_lose_percent(self):
#self = team object
team_lose_rate = [calculations here]
return team_lose_rate
In template:
{% for team in teams %}
team win percentage = {{ team.team_win_percent }}
team lose percentage = {{ team.team_lose_percent }}
{% endfor %}
Upvotes: 0