Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default null sorting behavior from PostgreSQL in the Django ORM

PostgreSQL by default considers NULL values as the highest, and thus sorts them first for descending queries and last for ascending ones.

You can modify this behaviour per query or at index creation by specifying 'NULLS LAST' or 'NULLS FIRST'.

How can I use this in conjunction with the Django ORM, without needing to use raw queries? I.e. when I add to my query_set something like qs.order_by("-publish_start"), how can I specify sorting for nulls? Or, as an alternative, upon field/index declaration.

like image 266
Carles Barrobés Avatar asked Sep 27 '12 15:09

Carles Barrobés


1 Answers

I figured out a way that accommodates DB engines that work either way (null as highest or lowest value) by using extra, making the null check a boolean, and when sorting booleans false < true seems to be universal:

qs = qs.extra(select={'null_start': "publish_start is null"},
              order_by=['null_start', '-publish_start'])
like image 153
Carles Barrobés Avatar answered Sep 27 '22 17:09

Carles Barrobés