2012-04-26 9 views
8

¿Es posible replicar este tipo de ordenación de SQL específico en el ORM de Django:Django order_by orden específico

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 

?

Respuesta

3

Puede hacerlo con extra() o más simple raw(), pero no pueden funcionar bien con una situación más compleja.

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 ...)') 

Para su código, el conjunto de condiciones es muy limitado, puede ordenar fácilmente en Python.

21

Dado que Django 1.8 tiene Conditional Expressions ya no es necesario usar 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') 
+1

very neat answer! –

Cuestiones relacionadas