How to order in django on two columns when one of the column is null

Viewed 29

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.

1 Answers

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 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')
Related