如何使用外键在django模板中重新组合

时间:2012-07-06 19:34:58

标签: django django-templates

我正在尝试显示按类别分组的成分列表。我得到了显示类别ID的列表,但我似乎无法继续前进。这是我的设置,非常感谢任何帮助。

# models.py
class IngredienceCategory(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name


class Ingredience(models.Model):
    name = models.CharField(max_length=30)
    category = models.ForeignKey(IngredienceCategory, null=True, blank=True)

    def __unicode__(self):
        return self.name


# views.py
def home(request):
    ingredients = Ingredience.objects.all()
    ingrcat = IngredienceCategory.objects.all()

    return render_to_response('home.html', {'ingredients': ingredients, 'ingrcat': ingrcat,})


# home.html template
<h2>List of items by category:</h2>
{% regroup ingredients|dictsort:"category_id" by category_id as ingr_by_cats %}
{% for category in ingr_by_cats %}
    <p>{{ category.grouper }}</p>
    <ul>
        {% for item in ingrcat.list %}
            <li><a href="#" id="{{ item.id }}">{{ item.name }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}

我目前得到的是什么:

<h2>List of items by category:</h2>
<p>1</p>
<ul></ul>

<p>2</p>
<ul></ul>

<p>3</p>
<ul></ul>

我想要实现的目标:

<h2>List of items by category:</h2>
<p>Category A</p>
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<p>Category B/p>
<ul>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

<p>Category C</p>
<ul>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item 9</li>
</ul>

1 个答案:

答案 0 :(得分:1)

你的问题在这里:

{% for item in ingrcat.list %}

你应该:

{% for item in category.list %}