Django order_by order

Is it possible to replicate this type of sql specific ordering in 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 

?

+8
django django-orm
source share
2 answers

You could do it w / extra() or simpler raw() , but they cannot work with a more complicated situation.

 qs.extra(select={'o':'(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)', order_by='o'} YourModel.raw('select ... order by (case ...)') 

For your code, the set of conditions is very limited; you can easily sort in Python.

+3
source share

Starting with Django 1.8 , you have conditional expressions , so you no longer need to use extra .

 from django.db.models import Case, When, Value, IntegerField SomeModel.objects.annotate( custom_order=Case( When(id=5, then=Value(1)), When(id=2, then=Value(2)), When(id=3, then=Value(3)), When(id=1, then=Value(4)), When(id=4, then=Value(5)), output_field=IntegerField(), ) ).order_by('custom_order') 
+22
source share

All Articles