I have the following code written in Python 2.6, with a Task class that has an optional due_date:
class Task(models.Model):
due_date = models.DateField(null = True, blank = True)
@staticmethod
def compare_by_due_date(t1, t2):
return due_date_cmp(t1.due_date, t2.due_date)
def due_date_cmp(t1, t2):
if t1 is None and t2 is None:
return 0;
if t1 is None:
return 1
if t2 is None:
return -1
return (t1 - t2).days
The reason why I extracted the comparison function outside the class is that I wanted to be able to test it without needing to build Task instances. I use compare_by_due_date in the following code to order tasks by increasing due date, with tasks having no due date at the end of the list:
tasks = Task.objects.all()
tasks.sort(Task.compare_by_due_date)
I understood from this answer on Code Review that I should be able to use keys instead of comparison function? Can you show me how?