Django admin: order by a nullable date, with null values at the end
I have a model with a DateTimeField which I would like to use to order the table in admin. Using ordering = ('-completed',)
in admin.py
works, but those with null
values come first in the sort. Is there a way to make them appear at the end instead?
So at the moment I have something like:
Column A Completed Column C
x - y
x - y
x Today's date y
x Yesterday's y
Is there a way to make it like this?
Column A Completed Column C
x Today's date y
x Yesterday's. y
x - y
x - y
You can use query expressions. To order by completed ascending and make null values sort last, use this:
from django.db.models import F
ordering = [F('completed').desc(nulls_last=True)]
Source :https://docs.djangoproject.com/en/dev/ref/models/options