Django: Adding “NULLS LAST” to query

前端 未结 8 2134
时光说笑
时光说笑 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:31

    We wanted to chain multiple order by statements, some ASC, some DESC all with NULLS LAST. There doesn't seem to be the possibility of this with order_by as it has the following call:

    obj.query.clear_ordering(force_empty=False)
    

    So you can do it with the following by appending add_ordering calls:

    qs = ATeamModel.objects.filter(whatever=1)
    qs.query.add_ordering(F('date_updated').desc(nulls_last=True))
    qs.query.add_ordering(F('date_created').desc(nulls_last=True))
    
    qs...
    

提交回复
热议问题