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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With