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)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With