Reputation: 176
I would like to order the dataset based upon the two columns let's say created_date and updated_date.
If updated_date is null it should order be using created_date otherwise using updated_date column.
Upvotes: 2
Views: 37
Reputation: 477160
You can work with a .annotate()
[Django-doc] and then .order_by(…)
[Django-doc]:
from django.db.models.functions import Coalesce
MyModel.objects.annotate(
my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')
Since django-3.2 you can work with .alias(…)
[Django-doc] to prevent calculating this both as column and in the ORDER BY
clause:
from django.db.models.functions import Coalesce
MyModel.objects.alias(
my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')
Upvotes: 2