2008-11-07 31 views
44

在我的views.py中,我構建了一個兩元組列表,其中元組中的第二項是另一個列表,如下所示:Django - 如何在模板中解開元組''for'循環

[ Product_Type_1, [ product_1, product_2 ], 
    Product_Type_2, [ product_3, product_4 ]] 

在普通的舊的Python,我可以迭代列表如下:

for product_type, products in list: 
    print product_type 
    for product in products: 
     print product 

我似乎無法做同樣的事情在我的Django的模板:

{% for product_type, products in product_list %} 
    print product_type 
    {% for product in products %} 
     print product 
    {% endfor %} 
{% endfor %} 

我從Django中得到這個錯誤:

捕獲的異常而呈現:壓縮參數#2必須支持迭代

當然,還有在模板中的一些HTML標記,不打印報表。 Django模板語言不支持元組解包功能嗎?還是我以錯誤的方式去做這件事?我所要做的只是顯示一個簡單的對象層次結構 - 有幾種產品類型,每種產品都有幾種產品(在models.py中,產品具有Product_type的外鍵,簡單的一對多關係)。

顯然,我對Django來說很新,所以任何輸入都將不勝感激。

+2

你說說元組,但你的問題僅包含列表。 python中它們是不同的東西。 – 2008-11-07 02:48:23

+0

你實際上沒有二元組。仔細看清你的清單,你有4個清單項目。至於強尼·布坎南指出的,你需要做的是: [Product_Type_1,[product_1,product_2],], [Product_Type_2,[product_3,product_4],],] 拿到兩元組的名單版本。 – MontyThreeCard 2017-03-17 14:03:09

回答

53

,如果你建立你的數據像這將是最好的{注意「(」和「)」可以「[」和「]」 repectively,交換一個是元組,一個用於名單}

[ (Product_Type_1, (product_1, product_2)), 
    (Product_Type_2, (product_3, product_4)) ] 

,並有模板做到這一點:

{% for product_type, products in product_type_list %} 
    {{ product_type }} 
    {% for product in products %} 
     {{ product }} 
    {% endfor %} 
{% endfor %} 

元組/列表被解壓在for循環的方式是基於列表迭代器返回的項目。 每次迭代只返回一個項目。在第一時間周圍循環,Product_Type_1,產品的第二個你的列表...

2

只需發送模板產品類型的列表,這樣做:

{% for product_type in product_type_list %} 
    {{ product_type }} 
    {% for product in product_type.products.all %} 
     {{ product }} 
    {% endfor %} 
{% endfor %} 

它已經同時一點點,所以我不記得確切的語法是什麼,讓我知道是否可行。檢查documentation

+0

+1:不要在視圖中過度 – 2008-11-07 03:10:00

+0

Chris Lawlor沒有解釋他是如何結束他的數據結構(這實際上不是兩元組列表),但是這種建議的方法會導致N + 1查詢顯示產品列表。 – 2008-11-07 20:14:24

+0

這裏是龍。使用此建議,您正在爲每個product_type單獨訪問數據庫。我懷疑最小化數據庫負載可能是首先使用元組背後的動機。 – btubbs 2009-12-03 01:05:55

5

您必須這樣使用:

{% for product_type, products in product_list.items %} 
    print product_type 
    {% for product in products %} 
     print product 
    {% endfor %} 
{% endfor %} 

不要忘記在詞典數據變量項

57

另一種方法如下。

如果一個人有一個元組列表說

mylst = [(a, b, c), (x, y, z), (l, m, n)], 

那麼可以在以下方式中的模板文件解壓這個名單。 在我的情況下,我有一個包含URL,標題和文檔摘要的元組列表。

{\% for item in mylst \%}  
    {{ item.0 }} {{ item.1}} {{ item.2 }}  
{\% endfor \%} 
1

如果你的元組中有一個固定的數字,你可以使用索引。我需要混合字典和值分別爲元組,所以我這樣做:

在視圖:

my_dict = {'parrot': ('dead', 'stone'), 'lumberjack': ('sleep_all_night', 'work_all_day')} 

在模板:

<select> 
    {% for key, tuple in my_dict.items %} 
    <option value="{{ key }}" important-attr="{{ tuple.0 }}">{{ tuple.1 }}</option> 
    {% endfor %} 
</select>