5

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)
2

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

1 Comment

In Django 1.8 you don't have to use extra you can use Conditional Expressions see here: stackoverflow.com/a/31611225/953553

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.