21

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

?

3 Answers 3

57

Since Django 1.8 you have Conditional Expressions so using extra is not necessary anymore.

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')
5
  • 1
    What is the difference between using annotate and then order_by, instead of directly setting the Case in order_by? Dec 30, 2020 at 14:39
  • @guival same issue for me, have an answer yet?
    – Bialomazur
    Feb 13, 2021 at 17:16
  • @Bialomazur I'm still not sure about the difference, I decided to simply put the Case inside the order_by, without doing the annotate, and it works. Feb 14, 2021 at 10:45
  • 1
    I've find this way being very useful also when combining the custom_order with additional ordering from other fields in the model, e.g. .order_by('custom_order', '-created_at')
    – msonsona
    Apr 27, 2021 at 10:09
  • The part that helped me here is the output_field. Django keeps changing how the inferrence works so it's best to just always include an output field.
    – munsu
    May 10, 2021 at 1:48
26

It is possible. Since Django 1.8 you can do in the following way:

from django.db.models import Case, When

ids = [5, 2, 3, 1, 4]
order = Case(*[When(id=id, then=pos) for pos, id in enumerate(ids)])
queryset = MyModel.objects.filter(id__in=ids).order_by(order)
2
  • I can't believe that worked. I have no idea how but that's SO programming for ya.
    – Kurt
    Apr 27, 2020 at 1:03
  • @Hiroki amazing! Nov 3, 2020 at 12:41
5

You could do it w/ extra() or more plain raw(), but they can not work well w/ more complex 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, condition set is very limited, you could sort in Python easily.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.