Django order_by specific order

前端 未结 3 555
余生分开走
余生分开走 2020-12-14 02:49

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 i         


        
3条回答
  •  臣服心动
    2020-12-14 03:52

    You could do it w/ extra() or more plain raw(), but they can not work well w/ more complex situation.

    qs.extra(select={'o':'(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)', order_by='o'}
    
    YourModel.raw('select ... order by (case ...)')
    

    For your code, condition set is very limited, you could sort in Python easily.

提交回复
热议问题