
Sort a Django Queryset by a Custom Order
Sorting a Django queryset by a custom order is trickier than it looks, and choosing the wrong solution for your use case can cripple your application’s performance. For example, let’s take a simple Todo model: class Todo(models.Model): class Priority(models.TextChoices): HIGH = "HIGH", _("High") MEDIUM = "MEDIUM", _("Medium") LOW = "LOW", _("Low") title = models.CharField(max_length=255) priority = models.CharField(max_length=10, choices=Priority.choices, db_index=True) done = models.BooleanField(default=False) And a list of todos: Id Title Priority Done 1 Add linters Medium Yes 2 Fix bug High No 3 Increase test coverage Medium No 4 Refactor views Low No 5 Run tests in CI High Yes Our query set goal is to order these items from high to low priority. For priority levels with multiple items, we’ll also order by title to keep the results consistent. The expected result should be the id’s in the following order: [2, 5, 1, 3, 4] ...



