QuerySet中的Django外键查找

时间:2016-12-15 02:25:40

标签: django

我正在为体育联盟写一个应用程序。我有团队模型和时间表。当用户选择一个团队时,他们可以看到团队的胜利,失败和关系。我想展示该团队的所有游戏。

Models.py

class Teams(models.Model):
    team = models.AutoField(primary_key=True)
    team_name = models.CharField(max_length=225, blank=True, null=True)
    sport_id = models.ForeignKey(Sports, models.DO_NOTHING, blank=True, null=True)
    division = models.CharField(max_length=225, blank=True, null=True)
    school = models.ForeignKey(School, models.DO_NOTHING, blank=True, null=True)
    win = models.IntegerField(blank=True, null=True, default=0)
    loss = models.IntegerField(blank=True, null=True, default=0)
    tie = models.IntegerField(blank=True, null=True, default=0)

    class Meta:
        managed = True
        db_table = 'teams'
    def __str__(self):
        return self.team_name

class Schedule(models.Model):
    match = models.AutoField(primary_key=True)
    match_date = models.DateField(blank=True, null=True)
    home = models.ForeignKey(Teams, related_name='home_set',  blank=True, null=True)
    away = models.ForeignKey(Teams, related_name='away_set', blank=True, null=True)
    home_score = models.IntegerField(blank=True, null=True)
    away_score = models.IntegerField(blank=True, null=True)
    class Meta:
        managed = True
        db_table = 'schedule'
    def __str__(self):
        return '%s at %s' % (self.away, self.home)

我的相关观点:

class TeamView(generic.TemplateView):
    template_name = "teamsports/teamview.html"

    def get_context_data(self, **kwargs):
        context = super(TeamView, self).get_context_data(**kwargs)
        q = self.request.GET.get('team_name')
        context['team'] = Teams.objects.get(team=q)
        context['game_list']=Schedule.objects.filter(home=q).values() | Schedule.objects.filter(away=q).values()
        return context

模板:

{% extends 'base.html' %}
{% block content %}
    <h1>Team Name: {{ team }}</h1>
    <h1>Wins: {{ team.win }}</h1>
    <h1>Losses: {{ team.loss }}</h1>

    <h1>Results: </h1>
        <h1>{% for game_list in game_list|dictsort:"match_date" %}</h1>
            <p>Date: {{game_list.match_date|date }} Home Team:  {{ game_list.home_team }}  Score: {{ game_list.home_score }} Away Team: {{ game_list.away_team }} Score {{ game_list.away_score|linebreaksbr }}</p>
            {% endfor %}

    <li><a href="/standings/">Pick another, ya jabroni</a></li>

{% endblock %}

这个有效!但是'game_list'中的团队显示为他们的身份证号码,而不是姓名。如何回顾我的团队模型以获得团队名称? 我尝试过的事情:

  1. 使用.values(team_name)使用主客场比赛编写大型查询。查询字段不匹配时出错,这对我来说很有意义。

  2. 为即将开始的游戏编写单独的视图并使用“include”。仍然存在将对方球队与比赛相匹配的问题。

  3. 我考虑过的事情:

    1. 撰写模板标签

    2. This或使用Q

    3. 任何指导都将不胜感激

1 个答案:

答案 0 :(得分:0)

为什么在所有查询集上使用values()?这将数据从Django模型实例 - 能够跟随外键 - 变成愚蠢的词典。

相反,您应该执行单个查询以获取所有匹配项,在查询本身中对其进行排序,然后返回。

from django.db.models import Q
game_list = Schedule.objects.filter(Q(home=q) | Q(away=q)).order_by('match_date').select_related('home', 'away')

select_related子句不是必需的,但可以更有效地跟随模板中的FK。

现在您的模板可以是:

{% for game in game_list %}
   <p>Date: {{ game.match_date|date }} Home Team:  {{ game.home.team_name }}  Score: {{ game.home_score }} Away Team: {{ game.away.team_name }} Score {{ game.away_score }}</p>
{% endfor %}