4

我有一个模型类别,它本身有一个 FK 引用。如何将数据发送到模板并使其看起来像这样

  • 第一类
    • 项目清单
    • 项目清单
  • 第 2 类
    • 项目清单
    • 项目清单
4

2 回答 2

3

你可能正在寻找这样的东西:

模型.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name_plural = 'categories'
        ordering = ['name']

视图.py

from myapp.models import Category # Change 'myapp' to your applications name.
from django.shortcuts import render_to_response

def category(request)
    cat_list = Category.objects.select_related().filter(parent=None)
    return render_to_response('template.html', { 'cat_list': cat_list })

模板.html

<ul>
{% for cat in cat_list %}
    <li>{{ cat.name }}</li>
    <ul>
    {% for item in cat.child.all %}
        <li>{{ item.name }}</li>
    {% endfor %}
    </ul>
{% endfor %}
</ul>
于 2009-03-30T13:26:45.197 回答
2

看起来您正在尝试在模板中进行递归。这可能会有所帮助: http ://www.undefinedfire.com/lab/recursion-django-templates/

于 2009-03-27T14:23:28.987 回答