Django Order By Date, but have "None" at end?

Garfonzo picture Garfonzo · Oct 13, 2011 · Viewed 14.6k times · Source

I have a model of work orders, with a field for when the work order is required by. To get a list of work orders, with those that are required early, I do this:

wo = Work_Order.objects.order_by('dateWORequired')

This works nicely, but ONLY if there is actually a value in that field. If there is no required date, then the value is None. Then, the list of work orders has all the None's at the top, and then the remaining work orders in proper order.

How can I get the None's at the bottom?

Answer

Ric W picture Ric W · Jun 24, 2017

Django 1.11 added this as a native feature. It's a little convoluted. It is documented.

Ordered with only one field, ascending:

wo = Work_Order.objects.order_by(F('dateWORequired').asc(nulls_last=True))

Ordered using two fields, both descending:

wo = Work_Order.objects.order_by(F('dateWORequired').desc(nulls_last=True), F('anotherfield').desc(nulls_last=True))