Skip to content
Advertisement

Django: Adding “NULLS LAST” to query

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(order_by=('-price', 'NULLS LAST'))

But I get

“Cannot resolve keyword ‘NULLS LAST’ into field”

Advertisement

Answer

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

This functionality has been added to 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.

Reference for Django 3.1: https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement