Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex ordering in django db query

I have the following entries in my database:

`title`            `status`
Titanic            WIP
Avatar             WIP
Terminator         Complete
Abyss              Default

I want to sort these objects by the status of the object: Default, then WIP, then Complete. The correct ordering would then be:

Abyss / Default
Avatar / WIP
Titanic / WIP
Terminator / Complete

How would I do the following db call?

Title.objects.order_by(status='Default', status='WIP', status='Complete',title)
like image 250
David542 Avatar asked Oct 06 '22 21:10

David542


1 Answers

To do this query, you can use django's extra:

titles = Title.objects.all()
ordered_query = titles.extra(select={
                'ordering':"(
                    case when status='Default' then 1 
                         when status='WIP' then 2
                         when status='Complete' then 3
                    end)"
                }).order_by('ordering', 'title')
like image 86
David542 Avatar answered Oct 10 '22 02:10

David542