Django order_by具体订单 [英] Django order_by specific order
本文介绍了Django order_by具体订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在django ORM中复制这种特定的sql排序:
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 id = 3 then 3
when id = 1 then 4
when id = 4 then 5
end) asc
?
推荐答案
你可以做到/ $ c> extra()或更多的简单 raw()
,但是它们无法正常工作/复杂的情况。
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 ...)')
对于您的代码,条件集非常有限,您可以轻松地在Python中排序。
For your code, condition set is very limited, you could sort in Python easily.
这篇关于Django order_by具体订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文