[Fixed]-Django queryset place of None/Null in orderby in Postgresql

1👍

Something like this should work.

select * from dude order by case when date is null then 1 else 0 end, date desc;
 test  |    date    
-------+------------
 test2 | 2001-01-04
 test2 | 2001-01-03
 test2 | 2001-01-02
 test2 | 2001-01-01
 test  | 
 test2 | 

example:

from django.db.models import Case, When, Value, IntegerField

SomeModel.objects.annotate(
    nulls_last=Case(
        When(time_returned__isnull=True, then=Value(1)),
        When(time_returned__isnull=False, then=Value(0)),
        output_field=IntegerField(),
    )
).order_by('nulls_last', '-time_returned')

from here: Django order_by specific order

Leave a comment