Sorting and indexing into a list in a Django template?

django, django-templates, python

Solution

As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.

Getting a sorted list of a physician's patients:

class Physician(Model):
   ...
   def sorted_patients(self):
      return self.patients.order_by('bed__room__unit',
                                    'bed__room__order',
                                    'bed__order')

And in the template, use `physician.sorted_patients` rather than `physician.patients`.

For the "display the notes of this note_type", it sounds like you might want a `notes` method for the note_type class. From your description I'm not sure if this is a model class or not, but the principle is the same:

class NoteType:
   ...
   def notes(self):
      return <calculate note set>

And then the template:

{% for note_type in note_types %}
   <div><h3>{{ note_type }}</h3></div>
   {% for note in note_type.notes %}
      <p>{{ note }}</p>
   {% endfor %}
   </div>
{% endfor %}

Problem

How can you perform complex sorting on an object before passing it to the template? For example, here is my view: ``` @login_required def overview(request): physicians = PhysicianGroup.objects.get(pk=physician_group).physicians for physician in physicians.all(): physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order') return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,})) ``` The physicians object is not ordered correctly in the template. Why not? Additionally, how do you index into a list inside the template? For example, (this doesn't work): ``` {% for note_type in note_types %} <div><h3>{{ note_type }}</h3> {% for notes in note_sets.index(parent.forloop.counter0) %} #only want to display the notes of this note_type! {% for note in notes %} <p>{{ note }}</p> {% endfor %} {% endfor %} </div> {% endfor %} ``` Thanks a bunch, Pete

Original source