django order_by query set, ascending and descending
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Ordering query results in Django is simple syntactically, but correctness depends on deterministic sorting strategy. This matters for pagination, feeds, and audit outputs where stable order is required. Good ordering design includes explicit direction, tie-breakers, and null handling.
Basic Ascending and Descending Sorting
Django uses order_by with field names:
- Ascending:
"created_at" - Descending:
"-created_at"
This generates SQL ORDER BY with expected direction.
Multi-Field Ordering for Stability
If first field has duplicates, pagination can become unstable. Add tie-breaker fields.
Including primary key as final tie-breaker is a common stability pattern.
Null Handling in Ordering
Database engines treat null ordering differently. Django supports explicit null placement through expression ordering.
Use explicit null behavior if your application depends on predictable placement.
Ordering Across Relations
You can order by related model fields using double underscores.
Ensure related columns are indexed when used heavily in ordering.
Dynamic Ordering from API Parameters
If sort field comes from request query params, validate against allow-list to avoid invalid field errors.
This keeps user-controlled sorting safe and deterministic.
Interaction with distinct
Ordering with distinct can produce database-specific behavior, especially on PostgreSQL with distinct("field"). Keep ordering aligned with distinct fields where required by backend rules.
When in doubt, inspect generated SQL and test on real database backend, not only SQLite.
Performance Considerations
Ordering large datasets can be expensive without indexes. Common improvements:
- Add indexes on frequently sorted fields.
- Avoid ordering on computed expressions unless needed.
- Use pagination with indexed order keys.
For very large tables, keyset pagination can outperform offset pagination with heavy sorting.
Testing Order Semantics
Include tests for:
- Direction correctness.
- Stable tie-break behavior.
- Null placement expectations.
- API parameter mapping.
Order-related regressions often appear after schema or index changes, so keep these tests in CI.
Keyset Pagination with Deterministic Order
Offset pagination with unstable ordering can skip or duplicate rows when new records arrive between requests. A safer pattern uses keyset pagination with explicit sort key and tie-breaker.
This keeps page boundaries deterministic even under concurrent inserts.
Query Inspection and Index Verification
Use str(queryset.query) to inspect generated SQL and verify that ordering columns have supporting indexes. For large tables, missing indexes on order keys can dominate response latency. Add index migrations for frequent sort fields and validate with database execution plans in staging before production rollout.

