0

我正在尝试显示按类别分组的成分列表。我已经显示了一个类别 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>
4

1 回答 1

2

你的问题在这里:

{% for item in ingrcat.list %}

你应该有:

{% for item in category.list %}
于 2012-07-06T19:42:57.887 回答