我正在尝试制作一个游戏应用程序,在该应用程序中,人们可以创建自己的团队,然后创建玩家并将玩家与特定团队相关联。问题是我如何只显示与之相关的团队中的球员。
高级谢谢您的帮助。
这是我的模特。py
class Team(models.Model):
name = models.CharField(max_length =240)
captain = models.CharField(max_length = 240)
v_captain = models.CharField(max_length = 240)
def get_absolute_url(self):
return reverse('games_app:detail',kwargs = {'pk':self.pk})
def __str__(self):
return self.name
class Players(models.Model):
over = models.CharField(max_length = 10)
batting = models.CharField(max_length = 100)
player_team = models.ForeignKey(Team,related_name = "teams")
这里是views.py
class List_Players(generic.ListView):
model = models.Players
template_name = 'games_app/players_list.html'
这是HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for i in object_list.player_team %}
<h1>Players :<strong>{{i.player_name}}</strong>
{% endfor %}
</body>
</html>
答案 0 :(得分:0)
它可能像是:-
class Team(models.Model):
name = models.CharField(max_length =240)
captain = models.CharField(max_length = 240)
v_captain = models.CharField(max_length = 240)
def get_absolute_url(self):
return reverse('games_app:detail',kwargs = {'pk':self.pk})
def __str__(self):
return self.name
class Players(models.Model):
over = models.CharField(max_length = 10)
batting = models.CharField(max_length = 100)
player_team = models.ForeignKey(Team,related_name = "teams")
这里是views.py
class Team_list(generic.ListView):
model = models.Team
template_name = '''make a new template here'''
context_object_name = 'team_list'
class List_Players(generic.DetailView):
model = models.Players
template_name = 'games_app/players_list.html'
context_object_name = 'team_detail'
这是HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>{{ team_detail.name }}</h1>
<h1>{{ team_detail.captain }}</h1>
<h1>{{ team_detail.v_captain }}</h1>
{% for players in team_detail.teams.all %}
<h1>Players :<strong>{{players.over}}</strong></h1>
{{ players.over }}
{{ players.batting }}
{% endfor %}
</body>
</html>
您必须为团队的ListView创建新的HTML文件,通过该标签,您可以使用标记将您的整个团队的详细信息视图链接到您的团队名称
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for teams in team_list %}
<h3>
<a href='{% url 'TYPE IN UR URL NAME' pk=teams.pk %}'>{{ teams.name }}</a>
</h3>
{% endfor %}
</body>
</html>
答案 1 :(得分:-1)
您需要遍历player
中的每个object_list
并打印出与之关联的团队的团队成员。
{% for player in object_list %}
<p> {{player.player_name}} </p>
{% for i in player.player_team.players %}
<h1>Players :<strong>{{i.player_name}}</strong>
{% endfor %}
{% endfor %}
但这是完全不推荐的。
这将导致大量的冗余信息。您应该使用Team
的{{1}}来显示每个团队的成员,或在ListView
的{{1}}上显示团队的成员。考虑更改页面的设计。