2017-04-04 69 views
0

我有這些模型建立:Django的模板雙列表

class Bar: 
    name = models.CharField() 
    foos = models.ManyToManyField(
     through='FooBar' 
     through_fields=('bar','foo') 
    ) 
class Foo: 
    name = models.CharField() 

class FooBar: 
    foo = models.ForeignKey(Foo) 
    bar = models.ForeignKey(Bar) 
    value = models.DecimalField() 

我試圖做一個雙列表顯示每個酒吧,其FOOS的價值,而n/a。如果酒吧沒有這個Foo的價值。

這就是我想要它看起來像:

 [Foo1] [Foo2] [Foo3] 
[Bar1] 4  n/a  n/a 
[Bar2] 3  n/a  9 
[Bar3] n/a  1  n/a 

這是我的代碼有:

<tr> 
{%for foo in foo_list%} 
    <th>{{foo.name}}</th> 
{%endfor%} 
</tr> 
{%for bar in bar_list%} 
    <th>{{bar.name}}</th> 
    {%for foo in foo_list%} 
     {%for foobar in bar.foobar_set.all%} 
      {%if foobar.foo == foo%} 
       <td>{{foobar.value}}</td> 
      {%endif%} 
     {%endfor%} 
    {%endfor%} 
</tr> 
{%endfor%} 

我無法弄清楚如何檢查是否foobar的對應美孚。

我可以做到這一點與for i in range(0,foo_list.count())和混亂i,但我不能在Django模板語言中做到這一點。

+1

在您的視圖中創建數據會更好。創建一個包含所有Foo和一個行列表的標題,以及關於Bar/Foo關係的所有數據。邏輯在視圖或模型中更好。不在模板中。 – Wilfried

+0

這基本上是我做的。只有我把它放在標籤中而不是視圖中 – pocpoc47

回答

0

我找到了解決方案,我創建了一個自定義模板標籤來處理邏輯。

@register.simple_tag 
def get_bar_foos_values(bar, foo_list): 
    i = 0 
    j = 0 
    output = [] 
    foobar_set = bar.foobar_set 
    while(i < foo_set.count()): 
     foo = foo_set.all()[i] 
     if(j < foobar_set.count() and foobar_set.all()[j].foo == foo): 
      output.append(foobar_set.all()[j].value) 
      i = i+1 
      j = j+1 
     else: 
      output.append("n/a") 
      i = i+1 
    return output 

而且在我的模板:

{%for bar in bar_list%} 
    <tr> 
     <th>{{bar.name}}</th> 
     {%get_bar_foos_values bar foo_set as foobars%} 
     {%for foobar in foobars%} 
      <td>{{foobar}}</td> 
     {%endfor%} 
    </tr> 
{%endfor%} 

它可能不是做的最好的方式,但它爲我工作。我做的唯一的事情就是將算法從模板移動到一個標籤,我可以用真正的Python編寫這個標籤,這樣就有了更大的靈活性。