小编典典

Django:向查询添加“ NULLS LAST”

django

我想通过使用Postgresql的“ NULLS LAST”选项对模型进行排序。怎么做?

我尝试了类似的东西

MyModel.objects.all().extra(order_by=('-price', 'NULLS LAST'))

但是我明白了

“无法将关键字’NULLS LAST’解析为字段”


阅读 526

收藏
2020-03-27

共1个答案

小编典典

from django.db.models import F  
MyModel.objects.all().order_by(F('price').desc(nulls_last=True))

此功能已添加到Django 1.11中。

https://docs.djangoproject.com/en/dev/releases/1.11/

Added the nulls_first and nulls_last parameters to Expression.asc() and desc() to control the ordering of null values.

2020-03-27