Is it possible to replicate this kind of specific sql ordering in the django ORM:
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
?
Is it possible to replicate this kind of specific sql ordering in the django ORM:
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
?
Since Django 1.8 you have Conditional Expressions so using
extra
is not necessary anymore.It is possible. Since Djnago 1.8 you can do in this way from django.db.models import Case, When
You could do it w/
extra()
or more plainraw()
, but they can not work well w/ more complex situation.For your code, condition set is very limited, you could sort in Python easily.