Django: Adding “NULLS LAST” to query

前端 未结 8 2186
时光说笑
时光说笑 2020-11-27 14:25

I would like to sort a model by using Postgresql\'s \"NULLS LAST\" option. How could it be done?

I tried something like

MyModel.objects.all().extra(ord

8条回答
  •  长情又很酷
    2020-11-27 14:56

    This was probably not available when the question was asked, but since Django 1.8 I think this is the best solution:

    from django.db.models import Coalesce, Value
    MyModel.objects.all().annotate(price_null=
        Coalesce('price', Value(-100000000)).order_by('-price_null')
    

    Coalesce selects the first non-null value, so you create a value price_null to order by which is just price but with null replaced by -100000000 (or +?).

提交回复
热议问题