Python 在模板中显示外键的值
我想在我的模板中显示外键的值,但在尝试渲染它时,它们显示为空白。我试图显示的值是来自Paciente属性的值,该属性通过外键连接到另一个应用程序中的患者模型,我将显示我实现此目标的尝试,但失败了,请您帮助我或告诉我我做错了什么: 意见 模型 样板 {%用于咨询中的患者。patient.all%}应为{%用于咨询中的患者。patient_set.all%}咨询模型中的Paciente对象关系不适用。这种关系是一对多的关系,这意味着耐心需要多方面的考虑 您可以从Paciente对象迭代向后引用关系 您也可以在模板中迭代反向关系Python 在模板中显示外键的值,python,django,Python,Django,我想在我的模板中显示外键的值,但在尝试渲染它时,它们显示为空白。我试图显示的值是来自Paciente属性的值,该属性通过外键连接到另一个应用程序中的患者模型,我将显示我实现此目标的尝试,但失败了,请您帮助我或告诉我我做错了什么: 意见 模型 样板 {%用于咨询中的患者。patient.all%}应为{%用于咨询中的患者。patient_set.all%}咨询模型中的Paciente对象关系不适用。这种关系是一对多的关系,这意味着耐心需要多方面的考虑 您可以从Paciente对象迭代向后引用关系
{% for consult in instance.consults.all %}
# Do everyting with consult object
{% endfor %}
或者可以执行以下操作直接调用Paciente对象
{%for consult in consults%}
<tr>
<td>{{consult.Paciente.Codigo}}</td>
<td>{{patient.Paciente.Nombres}} {{patient.Paciente.Apellidos}}</td>
<td>{{consult.Fecha}}</td>
<td>{{consult.Motivo}}</td>
<td>{{consult.Padecimiento}}</td>
</tr>
{%endfor%}
您需要将内部for循环从consults.patient.all%}中患者的{%更改为consults.Paciente_set.all%}中患者的{%。您可以通过在ForeignKey定义中添加相关的\u name属性来更改Paciente\u集合名称。is consults.Paciente.all不是吗?而不是consults.Patient.all?这也不起作用:所以我应该更改我的模型,将外键转换为OnetoMany字段以访问这些值?
{%extends 'base.html'%}
{%load staticfiles%}
{%block body_block%}
<link rel="stylesheet" href="{%static 'appointments/css/appointments_index.css'%}">
{%if consults%}
<h1 id="Heading">Consultas <h5 id="Date">{% now "j F Y" %}</h5></h1>
<table>
<thead>
<th>Codigo de Paciente</th>
<th>Paciente</th>
<th>Fecha</th>
<th>Motivo</th>
<th>Padecimiento</th>
</thead>
<tbody>
{%for consult in consults%}
{%for patient in consults.Patient.all%}
<tr>
<td>{{patient.Codigo}}</td>
<td>{{patient.Nombres}} {{patient.Apellidos}}</td>
<td>{{consult.Fecha}}</td>
<td>{{consult.Motivo}}</td>
<td>{{consult.Padecimiento}}</td>
</tr>
{%endfor%}
{%endfor%}
</tbody>
</table>
{%else%}
<h1 id="noregisters">No existen registros de consultas aun.</h1>
{%endif%}
<button id="Add"><a class="fas fa-plus" href="{%url 'addappointment'%}"></a></button>
{%endblock%}
class Consults(models.Model):
Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE, related_name="consults")
instance = Paciente.objects.first()
for consult in instance.consults.all():
# Do everyting with consult object
{% for consult in instance.consults.all %}
# Do everyting with consult object
{% endfor %}
{%for consult in consults%}
<tr>
<td>{{consult.Paciente.Codigo}}</td>
<td>{{patient.Paciente.Nombres}} {{patient.Paciente.Apellidos}}</td>
<td>{{consult.Fecha}}</td>
<td>{{consult.Motivo}}</td>
<td>{{consult.Padecimiento}}</td>
</tr>
{%endfor%}