访问外键(m2m)以呈现模板

时间:2013-08-25 00:50:59

标签: django

我认为与简单的FK查找相比,这可能是一个稍微复杂的问题。我试图在我的模板中输出一个列表,但是在显示它时遇到了一些困难。我认为它与我的模板中的for循环有关。任何帮助将不胜感激!

models.py

class Option(models.Model):
    relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
    option = models.CharField(max_length=300, verbose_name="treatment Options")

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

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

views.py

def diseasestateoptionlist(request, disease_id, state_id):

    state = get_object_or_404(State, pk=state_id)
    disease = get_object_or_404(Disease, pk=disease_id)

    stateoption = get_list_or_404(StateOption, parttstate=state_id) #probem may be here or in template.html

    diseasestateoptionlist = get_list_or_404(StateOption, parttstate=state_id)

    context = {'state': state, 'disease':disease, 'diseasestateoptionlist': diseasestateoptionlist, 'stateoption':stateoption}
    return render(request, "diseasestateoptionlist.html", context)

template.html

{{ disease }}
{{ state }}
{% if diseasestateoptionlist %}
 <ul>
{% for option in diseasestateoptionlist %}
   <li><a href="/drui_index/{{disease.id}}/state/option/{{state.id}}/list">{{stateoption.partoption}}</a></li> 
 #problem may be in the stateoption.partoption call
 {% endfor %}

更新: 使用for循环正确显示显示,但它不显示{{stateoption.partoption}}中的选项。所以{{disease}},{{state}正在渲染。 {diseasestateoptionlist}显示表中找到的值的数量。但是没有显示任何值(只是来自

  • 语句的要点)。

  • 1 个答案:

    答案 0 :(得分:1)

    {%选项在疾病状态选项列表中}}

    ... {{的 stateoption .partoption}} ...

    这两者必须相同。 :)

    问候