[Fixed]-Relating/adding data to a django object list

1๐Ÿ‘

โœ…

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 %}
๐Ÿ‘คuser1711330

0๐Ÿ‘

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 %}
๐Ÿ‘คGeo Jacob

Leave a comment