2012-07-08 79 views
2
  1. 我有一個模型Django的: '長' 對象不是可迭代

    class tournaments(models.Model): 
        # .... 
        total_rounds = models.IntegerField(max_length=11, blank=True, null=True) 
        # .... 
    
        def get_total_rounds_count(self): 
         return self.total_rounds 
    
  2. views.py:

    def tourney_view(request, offset): 
        # ..... 
        if (offset): 
         selected_tournament = tournaments.objects.get(id=offset) 
        return render_to_response('tournament.html', {'tournament': selected_tournament}) 
    
  3. 在 'tournament.html' 模板我試圖環超過total_rounds:

    {% for q in tournament.get_total_rounds_count%} 
    {% endfor %} 
    

並得到錯誤:'長'對象不可迭代 爲什麼?我場是IntegerField,我只是想遍歷整數值,但得到「沒有可迭代的」

+0

對於以後的文章:[?我如何格式化我的代碼塊(http://meta.stackexchange.com/q/22186) – 2012-07-08 13:02:02

+1

又是什麼'tournament.get_total_rounds_count'返回? (因爲我懷疑奧托就在這裏......) – 2012-07-08 13:02:03

+0

它返回self.total_rounds - 整數值 – Rusty 2012-07-08 13:04:03

回答

3

您可以使用此代碼片段:http://djangosnippets.org/snippets/1357/

或定義Tournament.get_total_rounds返回range(get_total_rounds_count)

+0

當我試圖使用「範圍」,我從Django解析器得到錯誤:無法解析其餘:'(tournament.get_total_rounds_count)'from'range(tournament.get_total_rounds_count)' – Rusty 2012-07-08 13:04:25

+0

我更新了答案 – 2012-07-08 13:14:44

0

那是因爲你不能使用for建設與數字

+0

如果我想循環「total_rounds」,應該怎麼做? – Rusty 2012-07-08 13:02:39

+0

@Rusty:你不能循環數字;你*可以*創建一個迭代「total_rounds」次數的循環,但這是一個不同的概念。 – 2012-07-08 13:03:36

+0

有沒有什麼方法可以在django模板中使用「range(tournament.get_total_rounds_count)」或其他東西? – Rusty 2012-07-08 13:06:40

2

呀,奧托的方式是最好的,只是更新您的函數返回的範圍內。

class tournaments(models.Model): 
    # .... 
    total_rounds = models.IntegerField(max_length=11, blank=True, null=True) 
    # .... 

    def get_total_rounds_count(self): 
     return range(self.total_rounds) 
+0

這是完美的,thx玫瑰油 – Rusty 2012-07-08 13:33:39