【问题标题】:Template not rendering correctly while iterating through foreign keys遍历外键时模板无法正确呈现
【发布时间】:2013-08-30 23:46:58
【问题描述】:

我正在尝试在我的模型中迭代我的 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)

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

...

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您的模板从不输出任何内容。

    你可能误解了{% for %}模板标签的用法。

    这个:

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

    输出&lt;li&gt; 几次。

    但是这个:

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

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

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 2015-03-20
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      相关资源
      最近更新 更多