迭代外键时模板无法正确呈现

时间:2013-08-30 23:46:59

标签: django django-templates

我试图在我的模型中迭代我的FK,以便通过各种表显示所有连接。我的模板呈现但不显示任何值。有什么想法吗?

models.py

class State(models.Model):
   state = models.CharField(max_length=255)
   relevantdisease = models.ForeignKey(Disease)
   relevantoption = models.ManyToManyField(Option, through='StateOption')

class StateOption(models.Model):
   partstate = models.ForeignKey(State)
   partoption = models.ForeignKey(Option)
   relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')

class StateOptionOutcome(models.Model):
   stateoption = models.ForeignKey(StateOption)
   relevantoutcome = models.ForeignKey(Outcome)
   outcomevalue = models.CharField(max_length=20)

views.py

def stateall(request, disease_id):

    disease = get_object_or_404(Disease, pk=disease_id)  
    states = State.objects.select_related().filter(relevantdisease=disease_id)

    context = {'disease':disease,'states': states}
    return render(request, "stateall.html", context)

template.html

{% for state in states %}
    <li>{% for i in state.stateoption_set.all %}</li>
        <li>{% for j in i.stateoptionoutcome_set.all %}</li>
        {% endfor %}
    {% endfor %}
{% endfor %}

我希望模板显示为:

State1<state>
   <li>partoption</li>
      <li>relevantoutcome: outcomevalue</li>

State2<state>
    <li>partoption</li>
      <li>relevantoutcome: outcomevalue</li>

...

1 个答案:

答案 0 :(得分:2)

您的模板永远不会输出任何内容。

您可能误解了{% for %}模板标记的使用。

此:

<li>{% for j in i.stateoptionoutcome_set.all %}</li>
{% endfor %}

输出<li>几次。

但是这个:

{% for j in i.stateoptionoutcome_set.all %}
    <li>{{ j.relevantoutcome }}: {{ j.outcomevalue }}</li>
{% endfor %}

将在StateOptionOutcome中找到每i.stateoptionoutcome_set.all行的一行。