有一个需求,比如说 某个 model Question 下有一个字段, priority,这个字段是个 int 型数据,然后获取筛选出来的数据需要 按照 priority 倒序排序,但是 priority = 3 的数据要置顶。
这种使用方法用 mysql 的语法很好解决:
order by priority = 3 desc
但是用 Django 自带的 model 的方法,可能是搜索的关键词不对,用中文搜索了好久没有结果,然后尝试使用 英文的关键词搜索:django order_by field equals some value mysql 然后就得到了一种解法,最终测试是有效的
用法如下:
from django.db.models import Case, Count, When
Question.objects.annotate(new_priority=Count(Case(When(priority=3, then=1)))).order_by("-new_priority")