I personally like to avoid sorting in Models, as this is more relevant to the view / view. I use sorting in render_to_response to sort by a single value or order_by for multi-valued sorting. Using sorting in the return statement allows me to split the difference between the view / template, since Django views are not completely controllers. In any case, this is only my preference. You can also use dictsort in the template to sort by one value.
You indicated that you want to sort using several values, first by the most recent date of birth, and then by name. To do this, I would use order_by in the view, and then comment out my return statement:
from django.shortcuts import render_to_response def view_persons(request): persons = Person.objects.all().order_by('-birthday', 'name') return render_to_response( 'view_persons.html', { 'persons': persons,
In the template, you have a little more than:
{% if persons %} <table> <thead> <tr> <th>Birthday</th> <th>Name</th> </tr> </thead> <tbody> {% for person in persons %} <tr> <td>{{ person.birthday }}</td> <td>{{ person.name }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <p>There are no people!</p> {% endif %}
source share