2013-04-06 44 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 %}