2013-04-06 31 views
2

其餘內的HTML我試圖執行雙重的,其中第二個從父親繼承的數據,如下:無法解析在Django {%for子句

{% for category in categories %} 
      <li><a href="/categories/{{ category.id }}/">{{ category.name }}</a> 
      {% for cat in category.objects.filter(parent=category.id) %} 
       {% if forloop.first %} 
       <ul class="noJS"> 
       {% endif %} 
        <li><a href="/categories/{{ cat.id }}">{{cat.name}}</a></li> 
       </ul> 
      {% endfor %} 

      {% endfor %} 

的問題是,我得到錯誤:

TemplateSyntaxError at/
Could not parse the remainder: '(parent=category.id))' from 'ca 

tegory.objects.filter(parent=category.id))' 
Request Method: GET 
Request URL: http://127.0.0.1:8000/ 
Django Version: 1.4.3 
Exception Type: TemplateSyntaxError 
Exception Value:  
Could not parse the remainder: '(parent=category.id))' from 'category.objects.filter(parent=category.id))' 

任何想法?

+0

這是錯的!你正在循環相同的模型? – catherine 2013-04-06 13:56:32

+0

我的模型繼承自身,就像樹 – Walucas 2013-04-06 13:59:17

+0

也許你應該嘗試另一種方式,而不是在模板內部過濾它 – catherine 2013-04-06 14:05:58

回答

0

我使用MPTT所以我剛纔所說的方法爲孩子節點:

 {% for cat in category.get_children %} 

,可從MPTT

1

理念:

models.py

class Category(models.Model): 
    ......... 

    def data(self): 
     return Category.objects.filter(id=self.id) 

模板

{% for category in categories %} 
<li><a href="/categories/{{ category.id }}/">{{ category.name }}</a> 
    {% for cat in category.data %} 
     {% if forloop.first %} 
     <ul class="noJS"> 
     {% endif %} 
      <li><a href="/categories/{{ cat.id }}">{{cat.name}}</a></li> 
     </ul> 
    {% endfor %} 
{% endfor %} 
0

因爲你有關係,甚至是自我指涉的一個,你會得到相反的關係的訪問。如果你還沒有設置related_name,那只是category_set。所以,你可以這樣做:

{% for cat in category.category_set.all %}