Django order_by specific order

前端 未结 3 558
余生分开走
余生分开走 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:43

    It is possible. Since Django 1.8 you can do in the following way:

    from django.db.models import Case, When
    
    ids = [5, 2, 3, 1, 4]
    order = Case(*[When(id=id, then=pos) for pos, id in enumerate(ids)])
    queryset = MyModel.objects.filter(id__in=ids).order_by(order)
    

提交回复
热议问题