[Fixed]-Usage of latest() method with field types other than date field (Django)

1👍

Here’s the source code for _earliest_or_latest, which powers the latest method. As you can see, it basically uses whatever field name you specify and tries its best to order your lookup by that field at the database level. It does this through the add_ordering method, which is documented in the source code here.

There’s nothing fancy at all going on under the hood – Django is just passing an ORDER BY and letting the database try to sort things out. That’s why you see inconsistent behavior between database environments, like how SQLite sorts nulls below non-nulls while MySQL and PostgreSQL do the reverse. Django isn’t really ordering the queryset, it’s the underlying database.

Things like dates, incremented IDs, etc. are easy for databases to order and therefore work well with latest. A UUIDField, on the other hand, probably wouldn’t work so well.

Leave a comment