New in Django 1.8 - Conditional Expressions Case() When()
inspired by this SO question… Imagine you want force Django to some custome ordering. And you wish to do it on big queryset, and don’t want nasty hacks with lambdas and lists in Python, but want use the power of your database. The database sudocode could look something like this: order by
(case
when id = 5 then 1
when id = 2 then 2
when id = 3 then 3
when id = 1 then 4
when id = 4 then 5
end) asc
Example solution using django 1.8 conditional expressions (Case, When) may be:
More about conditional expressions in Django: https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/