0

我试图在这里关注这个先前的问题:
Django: getting the list of related records for a list of objects

但似乎无法让它工作。

我得到了一份主人的名单,但没有得到一份宠物名字的名单。html 代码似乎没有执行第二个 FOR 循环。有任何想法吗?

模型.py

class Teacher(models.Model):
        teacher = models.CharField(max_length=300, verbose_name="teacher")

        def __unicode__(self):
          return self.teacher

class Owner(models.Model):
        relevantteacher = models.ForeignKey(Teacher, verbose_name="teacher")       
        owner = models.CharField(max_length=300, verbose_name="owner")

        def __unicode__(self):
          return self.owner

class PetName(models.Model):
        relevantowner = models.ForeignKey(Owner, verbose_name="owner")
        pet_name = models.CharField(max_length=50, verbose_name="pet Name")

    def __unicode__(self):
      return self.pet_name

视图.py

def ownersandteachers(request):   
   owners = Owner.objects.all()

   context = {'owners': owners}
   return render(request, 'ownersandpets.html', context)

模板

{% for i in owners %}
    {{ i.owner }} has pets:<br />
    {% for v in owners.petname_set.all %} //this doesn't seem to be executing
     - {{ v.pet_name }}<br />
    {% endfor %}
{% endfor %}
4

1 回答 1

1

你在做

{% for v in owners.petname_set.all %}

你应该在哪里做

{% for v in i.petname_set.all %}

owners是查询集,但您需要获取查询petname_set集中的单个对象,i在这种情况下。

i.petname_set另外,如果存在,我会建议进行条件检查。如果不是,请不要显示has pets:文本。

{% for i in owners %}
    {{ i.owner }} 
    {% if i.petname_set.count %} has pets:<br />
        {% for v in i.petname_set.all %} //this doesn't seem to be executing
         - {{ v.pet_name }}<br />
        {% endfor %}
    {% endif %}
{% endfor %}
于 2013-08-05T21:07:18.380 回答