我在每次比赛中都为同一位足球运动员添加进球而遇到麻烦。
我有课程
class Team(models.Model):
name = models.CharField()
class Footballer(models.Model):
name = models.CharField()
name_team = models.ForeignKey(Team)
class Match(models.Model):
number = models.IntegerField()
who = models.ForeingKey(Team,related_name="as_host")
guest = models.ForeingKey(Team,related_name="as_guest")
class Footballer_stat(models.Model):
id_footballer = models.ForeignKey(Footballer)
scored_goals = models.IntegerField('Strzelone Bramki')
我使用来自view.py的视图,它看起来像:
def how_much_goals(request):
x = Footballer.objects.all()
z = Footballer_stat.objects.order_by('-scored_goals')
sum = Pilkarz_stat.objects.aggregate(Sum("scored_goals"))
return render_to_response("goals.html",{"footballer":x,"footballer_goals":z, "Shooted_goals":sum["scored_goals__sum"]})
然后在goals.html中,我希望从每个匹配项目中收集目标,例如
Footballer Goals Results of adding goals the same ballers
Xxxx 2 Xxxx 3
Yyyy 3 (+) Yyyy 4
Xxxx 1 --->
Yyyy 1
我应该怎样做才能达到预期的效果?有什么想法吗?
答案 0 :(得分:0)
如果你在评论中说have to look like that
,那么我可能无法帮助你,你可以忽略这个答案。如果是doesnt have to look like that
,那么可能的解决方案就是:
class Team(models.Model):
name = models.CharField()
class Player(models.Model):
name = models.CharField()
team = models.ForeignKey(Team)
class Match(models.Model):
number = models.IntegerField()
who = models.ForeingKey(Team,related_name="as_host")
guest = models.ForeingKey(Team,related_name="as_guest")
class PlayerStats(models.Model):
player = models.ForeignKey(Player)
goals = models.IntegerField('Strzelone Bramki')
match = models.ForeignKey(Match)
class Meta:
unique_together = ('player', 'match')
现在,您可以非常轻松地为每场比赛添加每个球员的得分。此外,您只需要将一个QuerySet
传递给您的模板:
qs = PlayerStats.objects.select_related().all().extra(Sum('goals'))
qs.group_by = ('player', 'match')
for player in qs:
qs.player.name # player's name
qs.goals__sum # goals per match
自从我使用Django以来已经很长时间了,所以它可能不准确。