将数据关联/添加到django对象列表

时间:2015-12-08 11:49:01

标签: python django

我无法理解如何将其他信息与现有的Django列表相关联,以及我是否应该在我的模板或视图中以某种方式执行此操作。请参阅以下方案:

class Team(models.Model):
    team_name = models.CharField(max_length=200)

例如,在我看来,我正在检索所有体育比赛的列表并将其返回:

def get_teams(request):

    teams = Team.objects.all()

    context = RequestContext(request, {
            'teams': teams,
        })
        return context

我想向团队添加一些统计数据,然后我可以通过以下方式访问我的模板:

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

我正在努力理解的是如何将team_win_percentage和team_lose_percentage添加到我的团队列表中,以便我可以在我的模板中引用它们?

非常感谢任何指导!

2 个答案:

答案 0 :(得分:1)

你也可以为一些记录添加一些字段到模型查询结果,可以从模板中访问

{% for team in teams %}
    team win percentage = {{ team.team_win_percent }}
    team lose percentage = {{ team.team_lose_percent }}

{% endfor %}

在模板中

sudo docker build -t foo/bar .
sudo docker run foo/bar /bin/bash /path/to/my/script/test_report.sh
...

答案 1 :(得分:0)

你必须把它写成一个模型方法;

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

在模板中:

{% for team in teams %}
    team win percentage = {{ team.team_win_percent }}
    team lose percentage = {{ team.team_lose_percent }}

{% endfor %}