Django: Adding “NULLS LAST” to query

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

Leave a Comment