django打印循环值只有一次

ary*_*yan 3 python django templates loops

我有一个视图,我得到限制的约会列表..

def HospitalAppointmentView(request, pk, username, hdpk):
todays_appointments = DoctorAppointment.objects.filter(hospital__id=pk, doctor__id=hdpk, appointment_date=today).order_by("-appointment_date")[:5]

return render_to_response('doctor_appointment_list.html', {"todays_appointments": todays_appointments}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

在我的模板中:

{% for appointment in todays_appointments %}
    <h3>{{appointment.doctor.username}}<h3>
    <tr>
    <td>{{appointment.appointment_date}}</td>
    <td>{{appointment.first_name}} &nbsp;{{appointment.middle_name}} &nbsp; {{appointment.last_name}}</td>
    <td>{{appointment.user}}</td></tr>
    <a href="{% url "all_appointments" appointment.hospital.id appointment.doctor.id%}">
    See All</a>

{% endfor %}
Run Code Online (Sandbox Code Playgroud)

除了"全部看见"之外,它正确地显示5个约会重复5次,我想将医生的用户名作为标题,并且还要打印5次.

当我点击"查看全部"时,我想重定向到可以看到所有约会的页面.喜欢:

def HospitalAppointmentView(request, pk, username, hdpk):
todays_appointments = DoctorAppointment.objects.filter(hospital__id=pk, doctor__id=hdpk, appointment_date=today).order_by("-appointment_date")

return render_to_response('all_appointment.html', {"todays_appointments": todays_appointments}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

如果我在for循环之外写"See All",我就无法访问hospital.id和doctor.id并且在循环内部我得到"See All"5次,同样伴随着{{appointment.doctor.username}}.

如何在不打印的情况下重定向5次,并且网址中需要所有信息并且{{appointment.doctor.username}}被打印一次?

Roh*_*han 9

您可以使用{{forloop.first}}for,它将适用于第一次迭代.喜欢 ...

{% for appointment in todays_appointments %}

    {% if forloop.first %}
        <h3>{{appointment.doctor.username}}<h3>
    {%endif%}

    ...
{%endfor%}
Run Code Online (Sandbox Code Playgroud)