About Sorting a List of Model Instances with Lambda

Use lambda returning a tuple to sort a list of model instances by two or more fields, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from datetime import datetime

MIN_DATETIME = datetime.fromtimestamp(0)

last_logged_in_users = sorted(
    users, 
    key=(lambda obj: (
        -datetime.timestamp(obj.last_login or MIN_DATETIME), 
        obj.last_name, 
        obj.first_name,
    )),
)
for user in last_logged_in_users:
    print(user.get_full_name())

Note that 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