2012-08-16 85 views
4

我有我的數據庫中輸入以下內容:複雜的排序

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

我想通過物體的狀態,對這些對象進行排序:默認值,然後WIP,然後完成。然後正確的順序是:

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

我該怎麼做下面的數據庫調用?

Title.objects.order_by(status='Default', status='WIP', status='Complete',title) 
+3

http://stackoverflow.com/questions/10329849/django-order-by-specific-order – 2012-08-16 23:05:37

+0

謝謝你的! – David542 2012-08-16 23:17:14

+0

可能重複的[Django命令\ _特定順序](https://stackoverflow.com/questions/10329849/django-order-by-specific-order) – 2017-08-08 12:07:29

回答

3

要做到這一點查詢,你可以使用Django的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') 
+1

在Django ** 1.8 **您不必使用'額外'你可以使用[條件表達式](https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/)請參閱這裏:http://stackoverflow.com/a/31611225/953553 – andi 2015-07-24 13:43:51