Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django order_by specific order

Tags:

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

?

like image 874
MadMaardigan Avatar asked Apr 26 '12 08:04

MadMaardigan


People also ask

How do I sort objects in Django?

Django has order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field. In the Django model, there is one autogenerated 'id' field. You can use any of the fields (id name, mobile or name) to sort the queryset.

What is first () in Django?

In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers. first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

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')
like image 109
andilabs Avatar answered Sep 25 '22 00:09

andilabs