2

我的下一步是显示从数据库到 html 模板的查询。我可以提供一些基本信息,但我被外键查询卡住了。

这是我的代码示例:

这是我的模型:

class Player_Bios(models.Model):
    my_id            = models.SlugField(unique=True)
    player_id        = models.IntegerField(primary_key=True, max_length=50)    
    name             = models.CharField(max_length=50) 
    last             = models.CharField(max_length=50)

    def __unicode__(self):
       return self.player_id

class BatStat (models.Model):
    player_id           = models.ForeignKey('Player_Bios')
    team_id             = models.ForeignKey('Team')
    bat_stat_id         = models.CharField(max_length=50, unique=True)
    sport_code           = models.CharField(max_length=50, blank=True) 
    ab                  = models.IntegerField(max_length=50, null=True)

def __unicode__(self):
    return self.bat_stat_id

我的观点:

def SpecificPLayer(request, playerslug):
   player = Player_Bios.objects.get(player_id=playerslug) #this is the name, last and it is working fine
   playerStat = BatStat.objects.filter(player_id=playerslug) #Here I'm calling the foreign key
   print playerStat
   context = {'player' : player, 'today' : date.today(), 'playerStat' : playerStat }
   return render_to_response ('singleplayer.html', context,          context_instance=RequestContext(request))

我的 HTML 模板:

{% extends 'base.html' %}
{% block content %}

  <div id="singleplayer">
       <p>Name: {{ player.name|capfirst  }}</p>
       <p>Last Name: {{ player.last|capfirst  }}</p>

  </div>
        {% endfor %}


{% endblock %}

现在,当我打印 playerStat 时,我会从 player_id 获取所有 BatStat。在你的情况下,我得到以下信息:

[<BatStat: 40539520011>, <BatStat: 40539520021>, <BatStat: 40539520031>]

通过执行以下操作,我在 shell 上得到了我想要的结果:

playerStatID=BatStat.objects.filter(player_id='the player id here')
print playerStatID
[<BatStat: 40539520011>, <BatStat: 40539520021>, <BatStat: 40539520031>]
for i in playerStatID:
      playerStat= BatStat.objects.get(bat_stat_id=i)
      print BatStat.ab
      200

所以通过这样做我可以获得我需要的信息,现在我怎么能得到它,但是把它放在模板上。我不能在模板上使用循环来获取查询,所以我猜循环必须在视图上完成,但是如何。谢谢

4

1 回答 1

2

由于您有一个ForeignKeybetweenBatStatPlayer_Bios,您可以使用 a来获取单个玩家的batstat_set所有相关信息。BatStats

[此处的文档_set。][1]

所以你会有你views.py的:

def SpecificPLayer(request, playerslug):
    player = Player_Bios.objects.get(player_id=playerslug) #this is the name, last and it is working fine   
    batstats = player.batstat_set.all() 
    context = {'player' : player, 'today' : date.today(), 'batstats': batstats, }
    return render_to_response ('singleplayer.html', context,context_instance=RequestContext(request))

并在您的模板中:

{% for stat in batstats %}
    {{ stat.ab }}
{% endfor %}
于 2013-01-30T22:56:53.303 回答