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
@kabucey's answer is best for Django >= 1.11, but if you're using at least Django 1.8, 1.9 or 1.10, you can use a custom Func expression to achieve "NULLS Last" behaviour, as described at https://www.isotoma.com/blog/2015/11/23/sorting-querysets-with-nulls-in-django/:
from django.db.models import Func
class IsNull(Func):
template = '%(expressions)s IS NULL'
MyModel.objects.all().annotate(
price_isnull=IsNull('price_isnull'),
).order_by(
'price_isnull',
'-price',
)
The first order_by argument sorts the list in ascending order by price_isnull, forcing null-price items to the end of the list since True > False.