0

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

模型.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)

视图.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)

模板.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>

...
4

1 回答 1

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

于 2013-08-31T00:08:40.490 回答