2016-10-25 33 views
1

我除了這個問題是相對容易的,但因爲我是新的Django我掙扎。Django模板 - 循環QuerySet沒有創建多個時間段的

我收到了一個給模板的QuerySet。基本上我想創建一個足球(足球)表。但總的來說,我想了解這個概念。

因此,對於團隊查詢集中的每個團隊,數據應填充在5個相應的列中。目前我通過在每一列中添加一個for循環來解決這個問題。但是,我認爲它看起來很醜並且效率不高。此外,我想編輯前三個循環的ID。

所以我在找什麼:一個可能性爲div設置for循環,但不在每個循環中創建div。

喜歡的東西:

{%for team in teams %} 

    <div id="position">team.position</div> 
    <div id="name">team.name</div> 
    ... 
{% endfor %} 

除了添加類似:

{% if forloop.counter0 == 0|1|2 %} 
    add id/class to div row 
{% endif %} 

是這裏最聰明的方式,增加了變量的類,意思等級= {{XYZ}}?

模板看起來像這樣。

<div class="row"> 
      <div class="col-md-2" id="position">{% for tea in teams %}{{tea.league_position}}</br>{% endfor %}</div> 
      <div class="col-md-4" id="name">{% for tea in teams %}{{tea.team_name}}</br>{% endfor %}</div> 
      <div class="col-md-2" id="points">{% for tea in teams %}{{tea.league_points}}</br>{% endfor %}</div> 
      <div class="col-md-2" id="goals">{% for tea in teams %}{{tea.goals_shot}}</br>{% endfor %}</div>  
      <div class="col-md-2" id="received">{% for tea in teams %}{{tea.goals_received}}</br>{% endfor %}</div> 
</div> 

謝謝您的幫助!!!!! 西蒙

+1

,我不認爲這是有可能這樣 - 你爲什麼不希望使用'

'?這樣做會更容易 –

+0

的確如此,但我認爲在其他情況下我會遇到同樣的問題。我認爲可能只在第一個循環中設置div,並將其餘部分放入其中。 – svmon

+0

當然,你可以但你必須記住,那麼你會得到一系列封閉的div - 它可以是好的,如果他們會有'col-xs-4'類和總和爲12(因爲div創建一列總是在另一個相同類型) - 無論如何對我來說,這不值得你的時間。使用'

' - 這就是爲什麼這個標籤存在;) –

回答

0

你正在建立一個表格。改用表格。

<table> 
    <tr> 
     <th>Position</th> 
     <th>Name</th> 
     <th>Points</th> 
     <th>Shots</th> 
     <th>Goals against</th> 
    </tr> 
    {% for t in teams %} 
    <tr> 
     <td>{{ t.league_position }}</td> 
     <td>{{ t.team_name }}</td> 
     <td>{{ t.league_points }}</td> 
     <td>{{ t.goals_shot }}</td> 
     <td>{{ t.goals_received }}</td> 
    </tr> 
    {% endfor %} 
</table> 
+0

這不是我正在尋找的東西,但是對於這個特定的情況它很合適。謝謝! – svmon

0

如果你不想包含的div那麼唯一可能的方式是做一個Ajax請求分別填充列...

下面是未經檢驗的(也可能是錯誤的),但它應該給我一個想法我的意思

$.get('my_get_teams_url', function(data){ 
    for(i = 0; i < data.teams.length; i++) 
    { 
     $('#position').append(data.teams[i].position); 
     $('#name').append(data.teams[i].name); 
    } 
});