9

我无法理解这一点。我需要以某种方式访问​​父循环中的对象,但我不确定如何。到目前为止,这是我想出的。我用XXX标记了代码中的问题区域:

模板:

{% for item in ingrcat %}
    <h2>{{ item.name }}</h2>
    <ul>
        {% for ingr in XXX %}
        <li><a href="#" id="i{{ ingr.id }}">{{ ingr.name }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}

XXX - 应该是属于成分类别的成分列表,该成分类别当前正在父循环中循环。

看法:

def home(request):
    if request.user.is_authenticated():
        username = request.user.username
        email = request.user.email
        foods = Food.objects.filter(user=request.user).order_by('name')
        ingredients = Ingredience.objects.filter(user=request.user).order_by('name')
        ingrcat = IngredienceCategory.objects.filter(user=request.user)

        context = {}
        for i in ingredients:
            context[i.category.name.lower()] = context.get(i.category.name.lower(), []) + [i]

        newcontext = {'foods': foods, 'ingredients': ingredients, 'ingrcat': ingrcat, 'username': username, 'email': email,}
    else:
        context = {}
        newcontext = {}

    context = dict(context.items() + newcontext.items())

    return render_to_response('home.html', context, context_instance=RequestContext(request))

楷模:

from django.db import models
from django.contrib.auth.models import User

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

    class Meta:
        verbose_name_plural = "Ingredience Categories"

    def __unicode__(self):
        return self.name


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

    class Meta:
         verbose_name_plural = "Ingredients"

    def __unicode__(self):
        return self.name


class Food(models.Model):
    name = models.CharField(max_length=30)
    ingredients = models.ManyToManyField(Ingredience)
    html_id = models.CharField(max_length=30, null=True, blank=True)
    user = models.ForeignKey(User, null=True, blank=True)

    class Meta:
        verbose_name_plural = "Foods"

    def __unicode__(self):
        return self.name
4

2 回答 2

15

您可以使用反向关系。

{% for item in ingrcat %}
<h2>{{ item.name }}</h2>
<ul>
    {% for ingr in item.ingredience_set.all %}
    <li><a href="#" id="i{{ ingr.id }}">{{ ingr.name }}</a></li>
    {% endfor %}
</ul>
{% endfor %}

请参阅文档:

https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

于 2012-11-05T12:58:36.047 回答
1

在 obj.manytomanyfield 上做 get_queryset

{% for item in ingrcat %}
<h2>{{ item.name }}</h2>
<ul>
    {% for ingr in item.ingredients.get_queryset %}
    <li><a href="#" id="i{{ ingr.id }}">{{ ingr.name }}</a></li>
    {% endfor %}
</ul>
{% endfor %}
于 2021-01-21T18:17:55.457 回答