Reputation: 49
I want to order my data in Django admin in descending order, but I want the null field which represent task that has not ended to come to the top first following the descending order of dates.
for Example
End date is listed like this
--
Dec 5 ,2018
March 2,2017
and not like this
Dec 5 ,2018
March 2,2017
--
in my view.py I have tried in this way
class TaskViewset(Viewsets.ModelViewset)
queryset = Task.objects.filter(end_date__isnull=True).order_by("-end_date")
This limit what was return back to only data where end_date is null.
How can i do this to return data including those Task that have ended while returning the not ended task first?
Thanks for your help.
Upvotes: 2
Views: 3253
Reputation: 15738
From django documentation
Using F() to sort null values
Use F() and the nulls_first or nulls_last keyword argument to Expression.asc() or desc() to control the ordering of a field’s null values. By default, the ordering depends on your database.
For example, to sort companies that haven’t been contacted (last_contacted is null) after companies that have been contacted:
from django.db.models import F Company.objects.order_by(F('last_contacted').desc(nulls_last=True))
Upvotes: 6