Django,如何迭代不同长度的一个到多个字段

时间:2014-09-03 09:48:45

标签: python django

我对Django很新,我正在尝试创建一个显示网球比赛结果的应用程序。到目前为止,除了我的信念,我已经设法破解了一些有效的代码。

然而,我现在遇到了一个问题,虽然目前我想在模板中列出匹配及其分数,但每个匹配的集合数量可能不同,当我遍历它们时,我得到一个索引错误。有些比赛可能有2组,其他有3,4或5 ......如果一名运动员退役,可能只有一些比赛。

我有匹配和每组的模型,类似这样。 (我可以获得播放器的匹配日期,匹配,结果和Set1等,因为这些列表都具有相同数量的值。但是,作为示例的set3列表的长度要短得多并导致错误。 ):

models.py

class Match(models.Model):
    match_ID = models.AutoField(primary_key=True)
    match_date = models.DateField()
    players = models.ManyToManyField(Team, through='MatchStats', related_name='pim')
    hometeam = models.ForeignKey(Team, to_field='teamname', related_name='hometeam')
    awayteam = models.ForeignKey(Team, to_field='teamname', related_name='awayteam')
    hometeam_sets = models.IntegerField()
    awayteam_sets = models.IntegerField()

class Set(models.Model):
    set_ID = models.AutoField(primary_key=True)
    match = models.ForeignKey(Match)
    set_number = models.IntegerField()
    hometeam_games = models.IntegerField(default=0)
    awayteam_games = models.IntegerField(default=0)

views.py

def playermatches(request, player_ID):
    context = RequestContext(request)
    p = get_object_or_404(Player, pk=player_ID)
    match_list = Match.objects.filter(players=player_ID).order_by('-match_date')[:100]

    i = len(match_list)
    j = 0

    #This works as all test matches have a 1st set!
    s1_list = Set.objects.filter(match=match_list, set_number=1).order_by(-match__match_date')[:100]
    """
    I am totally out of ideas as to what I might do next though. 
    Tried various things like 'if exists', 'try except IndexError etc'. 
    Below was the last thing I tried which failed yet again.
    """

    s3_list = []
    while j < i:
        s3 = Set.objects.filter(match=match_list, set_number=3)[j]
        if s3:
            s3_list.append(s2)
        else:
            s3 = Set.objects.filter(set_ID=1)
            s3_list.append(s3)

    lst1 = match_list
    lst2 = result_list
    lst3 = s1_list
    ...
    lst5 = s3_list

    mandr = zip(lst1, lst2, lst3,... lst5)

    context_dict = {...}
    return render_to_response('stats/players.html', context_dict, context)

template.html

{% if matches %}
    <ul>
        {% for match, team, s1, s2 in mandr %}
        <li>{{ match.match_date }} <a href="/stats/match/{{ match.match_ID }}/">{{ match.hometeam }} vs. {{ match.awayteam }}</a> ( {{ team.result }} )</li>
        <li>{{ match.hometeam_sets }}:{{ match.awayteam_sets }} -- {{ s1.hometeam_games }}-{{ s1.awayteam_games }} {{ s3.hometeam_games }}-{{ s3.awayteam_games }}</li>
        {% endfor %}
    </ul>
{% else %}
    <br/>
    <strong>There are currently no matches in the system - try again tomorrow!</strong>
{% endif %}

2 个答案:

答案 0 :(得分:0)

不要将匹配列表,结果列表与剩余列表混合在一起。将它们作为视图中的单独对象传递,并在模板中迭代它们。

更改您的观点&amp;模板如下。

<强> views.py

m_list = match_list
r_list = result_list

list1 = s1_list
list2 = s2_list
..............
list5 = s3_list

mandr = zip(m_list, r_list)
my_lists = zip(list1, list2, ..., lst5)

<强> templates.py

{% if matches %}
<ul>
    {% for match, team in mandr %}
    <li>{{ match.match_date }} <a href="/stats/match/{{ match.match_ID }}/">
    {{ match.hometeam }} vs. {{ match.awayteam }}</a> ( {{ team.result }} )</li>
    <li>{{ match.hometeam_sets }}:{{ match.awayteam_sets }} --
        {% for lst in my_lists %} 
            <li>{{ lst.hometeam_games }}</li>
        {% endfor %}
    {% endfor %}
</ul>
{% else %}
    <br/>
    <strong>There are currently no matches in the system - try again tomorrow!</strong>
{% endif %}

答案 1 :(得分:0)

最后不需要任何太花哨的东西。意识到我需要通过外键为每个匹配查找相关集合......然后简单地迭代模板中的那些。

{% for match in mandr %}
    {% for set in match.sets.all %}
        {{ set.hometeam_games }}:{{ set.awayteam_games }}
    {% endfor %}
{% endfor %}