Django: Adding “NULLS LAST” to query

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

    Closest thing I've found is doing it on two steps. First ordering on the populated field and then on the nulls:

    Via this gist (itself via these django logs):

    all_projects = Project.objects.select_related().filter(
        company=company).order_by('-date_due')
    
    q = all_projects.extra(select={'date_due_null': 'date_due is null'})
    q = q.extra(order_by=['date_due_null'])
    print q.query
    

    Caution: note the warnings regarding extra(), and that it may be deprecated in the future.

提交回复
热议问题