开发者

Django Views Join Models Using Foreign Key

开发者 https://www.devze.com 2022-12-16 18:19 出处:网络
I have the following models defined: class Player(models.Model): Team = models.ForeignKey(Team) Name = models.CharField(max_length=200)

I have the following models defined:

class Player(models.Model):
    Team = models.ForeignKey(Team)
    Name = models.CharField(max_length=200)
    Position = models.CharField(max_length=3)
    ... snip ...

What I would like to output in a view is a list of players who are i开发者_C百科n the team with id = 1.

I have tried things such as:

{% for player in userTeam.userTeamSquad %}
       <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr>
{% endfor %}

But can't get it right.


You need a view that looks something like this:

def players(request):
    players_in_team_one = Player.objects.filter(Team__pk = 1)
    return render_to_response('players.html', {'players': players_in_team_one})

and you can loop through it like this in players.html:

{% for player in players %}
       <tr><td>{{ player.Name }}</td><td> {{ player.Position }}</td></tr>
{% endfor %}

p.s. As a matter of style, it's more standard to use all_lowercase_names_with_underscores as field names.

0

精彩评论

暂无评论...
验证码 换一张
取 消