简体   繁体   中英

django print loop value only once

I have a view where I am getting the list of appointments with limit..

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))

In my template:

{% 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 %}

Its showing the 5 appointments correctly except "See All" is repeated 5 times and I want to make doctor's username as title and its also being printed 5 times.

When I click "See All" I want to redirect to the page where all appointments can be seen. Like:

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))

If I write "See All" outside the for loop I cant access the hospital.id and doctor.id and inside the loop I m getting "See All " 5 times and same goes with {{appointment.doctor.username}}.

How can I redirect without being printed 5 times with all information needed in the url and {{appointment.doctor.username}} being printed once?

You can use {{forloop.first}} for, it will be true for 1st iteration. Like ...

{% for appointment in todays_appointments %}

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

    ...
{%endfor%}
{{todays_appointments.0.doctor.username}}

and your normal loop.

{% for appointment in todays_appointments %}
 ....
{% endfor %}

but rohan's answer is wiser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM