在HTML中我试图执行double 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 :(得分: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 %}
答案 1 :(得分:0)
因为你有一种关系,即使是一种自我指涉的关系,你也会获得反向关系的访问者。如果您尚未设置related_name
,则只会category_set
。所以你可以这样做:
{% for cat in category.category_set.all %}
答案 2 :(得分:0)
我正在使用MPTT所以我只是为子节点调用一个方法:
{% for cat in category.get_children %}
可从MPTT获得