About Sorting a List of Model Instances with Attrgetter

Use operator.attrgetter to sort a list of model instances by one or more fields, for example:

1
2
3
4
5
6
7
from operator import attrgetter

for user in sorted(
    users, 
    key=attrgetter("last_name", "first_name")
):
    print(user.get_full_name())

Note that this option doesn't work if your fields are nullable. And whenever possible, you should instead do the sorting at the database level, that is, QuerySets.

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Python 3