I used a paying_for_college query of notifications as a test of where to use an order_by
clause.
We have 193K notifications, unorderd by default. 179K of them have '1' in their oid
field.
from paying_for_college.models import Notification
nosort = Notification.objects.filter(oid__contains='1')
first = Notification.objects.order_by('timestamp').filter(oid__contains='1')
last = Notification.objects.filter(oid__contains='1').order_by('timestamp')
str(nosort.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url",
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid",
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors",
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent",
"paying_for_college_notification"."log"
FROM "paying_for_college_notification"
WHERE "paying_for_college_notification"."oid"::text LIKE %1%
str(first.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url",
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid",
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors",
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent",
"paying_for_college_notification"."log"
FROM "paying_for_college_notification"
WHERE "paying_for_college_notification"."oid"::text LIKE %1%
ORDER BY "paying_for_college_notification"."timestamp" ASC
str(last.query)
SELECT "paying_for_college_notification"."id", "paying_for_college_notification"."url",
"paying_for_college_notification"."institution_id", "paying_for_college_notification"."oid",
"paying_for_college_notification"."timestamp", "paying_for_college_notification"."errors",
"paying_for_college_notification"."emails", "paying_for_college_notification"."sent",
"paying_for_college_notification"."log"
FROM "paying_for_college_notification"
WHERE "paying_for_college_notification"."oid"::text LIKE %1%
ORDER BY "paying_for_college_notification"."timestamp" ASC